Reputation: 35
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
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:
$[ ]
and let
. Neither is good form in modern scripting.echo $var
if the values themselves, or the value of the IFS variable, are unknown or not controlled. See BashPitfalls #14.Upvotes: 4
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