i have variables from x0
to x9
and i created a random number randomnum=$((RANDOM % 10))
now i want to put them as:-
#! /bin/bash
x0="1"
x1="1"
x2="1"
x3="1"
x4="1"
x5="0"
x6="0"
x7="0"
x8="0"
x9="0"
player1=1
if [[ $x$randomnum == $player1 ]]; then
echo "it end!"
fi
here i want to combine $x
and $randomnumber
. how would i do that?
CodePudding user response:
You have a couple of choices.
Do to exactly what you want, you can use the eval
statement to take the result of an expression and execute it as a shell command. For example:
eval selected=\$x$randomnum
if [[ $selected == $player ]]; then
...
fi
The expression passed to the eval
statement becomes selected=$x1
, which we then evalute, setting selected
to the value of $x1
.
But a better structure for this would be to use an array variable instead of a series of named variables, something like:
randomnum=$(( RANDOM % 10 ))
x=( 1 1 1 1 1 0 0 0 0 0 )
player1 = 1
if [[ ${x[$randomnum]} == $player1 ]]; then
...
fi
CodePudding user response:
You need to do this :-
#!/bin/bash
a='1'
b=5
c="${a}${b}"
echo $c
d=15
if [[ $c == $d ]]; then
echo "it end!"
fi