2

I need print value of (i.e. CadetBlue) random var from COLOUR_* I tried"

echo $COLOUR_${NUMBER}
echo "$COLOUR_${NUMBER}"

and many others and none is working.

I Have bash:

#!/bin/bash
NUMBER=$[ ( $RANDOM % 9 )  + 1 ]
echo $NUMBER

COLOUR_1=AliceBlue
COLOUR_2=AntiqueWhite
COLOUR_3=AntiqueWhite1
COLOUR_4=AntiqueWhite2
COLOUR_5=AntiqueWhite3
COLOUR_6=AntiqueWhite4
COLOUR_7=BlanchedAlmond
COLOUR_8=BlueViolet
COLOUR_9=CadetBlue

echo $COLOUR_$NUMBER
1
  • $[...] is a deprecated syntax; use $((...)) instead. Commented Jul 18, 2013 at 12:30

2 Answers 2

5

Instead of saying

echo $COLOUR_$NUMBER

say:

color=COLOUR_${NUMBER}
echo ${!color}

You can read more about indirect expansion here.

Sign up to request clarification or add additional context in comments.

Comments

5

Or use an array:

#!/bin/bash
NUMBER=$(( $RANDOM % 9 ))
echo $NUMBER

COLOURS=(AliceBlue AntiqueWhite AntiqueWhite1 AntiqueWhite2
    AntiqueWhite3 AntiqueWhite4 BlanchedAlmond BlueViolet CadetBlue)

echo ${COLOURS[$NUMBER]}

1 Comment

+1 although you don't need the line continuation when declaring the array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.