Jared
Jared

Reputation: 35

Assign Element of Array to Variable Bash

I'm trying to assign the element of an array to a variable so I can use it later. For example:

constraints=("A" "B" "C" "E" "Q" "P" "S")

constraint=A

... a loop ...

rand=$[$RANDOM % ${#constraints[@]}]

let constraint="${constraints[${rand}]}"

echo $constraint

... end of loop ...

If the array is all numeric values, it works. But if they are strings the echo always outputs 0. Why?

Upvotes: 1

Views: 206

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295766

let is only for arithmetic operations. Your strings have no numeric value (unless they name variables which themselves have numeric values), so they all evaluate to 0 in that context.

Make it:

constraint="${constraints[${rand}]}"

...with no let.


In context, this might look like:

constraints=(A B C E Q P S)
rand=$(( RANDOM % ${#constraints[@]} ))
constraint=${constraints[${rand}]}
echo "$constraint"

Note:

  • See the bash-hackers' wiki page on obsolete syntax for discussion of $[ ] and let. Neither is good form in modern scripting.
  • Quotes are not needed (though it's safe to use them, and good practice to do so whenever unsure!) on items that parse unambiguously to a single word during an assignment, as both string-splitting and glob expansion are turned off by default in this context.
  • Quotes are needed for echo $var if the values themselves, or the value of the IFS variable, are unknown or not controlled. See BashPitfalls #14.

Upvotes: 4

Pedro
Pedro

Reputation: 116

Get rid of the "let."

constraints=("A" "B" "C" "E" "Q" "P" "S")
constraint=A
rand=$[$RANDOM % ${#constraints[@]}]
constraint="${constraints[${rand}]}"
echo $constraint

Upvotes: 2

Related Questions