Thursday 30 April 2015

Bash Dereference Concatenated Variable Name

Cited from Dereference concatenated variable name

FRUITS="BANANA APPLE ORANGE"

BANANA_COLOUR="Yellow"
APPLE_COLOUR="Green or Red"
ORANGE_COLOUR="Blue"

for fruit in $FRUITS ;do
    eval echo $fruit is \$${fruit}_COLOUR
done

'The eval simply tells bash to make a second evaluation of the following statement (ie. one more that its normal evaluation).. The \$ survives the first evaluation as $, and the next evaluation then treats this $ as the start of a variable name, which resolves to "Yellow", etc..'.

No comments:

Post a Comment