Friday, March 25, 2011

Element in Array with Bash?

I recently found myself editing a rather long conditional evaluation in Bash that was essentially comparing a variable, $color, against several valid matches. If $color didn't match any of them, the condition evaluated to true. I was a little disappointed with the prospect of maintaining it and the stretch of ORs and ==s across my screen. In a "real" scripting language, I would just use an array and check if $color was an element. Then I realized that Bash lets me use an array, just a little differently. With a combination of echo and grep, I got the job done.

declare -a valid_colors=( 'green' 'red' 'blue' )

echo "${valid_colors[@]}" | grep -qv "$color"
if [ $? -eq 0 ]; then
  # Do your stuff
fi

No comments:

Post a Comment