Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to combine two variables in bash

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading