0

i have variable $var and $var2. I created a random number via rand=$((RANDOM % 10)).

now if I want to combine $var and $var2 and assign value of $rand to them:-

#! /bin/bash

rand=$((RANDOM % 10))
var2=1

var_$var2="$rand"

And i want to compare them too:-

[[ $var_$var2 -eq 0 ]] && echo "Its zero"

This obviously doesn't work, then how exactly can I declare and Compare two variable dynamically?

Random Guy
  • 53
  • 10

2 Answers2

2

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
larsks
  • 277,717
  • 41
  • 399
  • 399
0

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
Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67