Variables

when

N1=1
a1=18

Piece of code :

f1=$"a"$N1
echo $f1

Im expecting output as 18 .. but it is not working as expected

To get the results you were expecting, you need:

eval f1=\$"a"$N1
echo $f1

If N1 can be set from user input (rather than directly set by your script), eval can be dangerous.

1 Like

eval can be dangerous - Can you explain on this

What are you actually trying to do? Use the value of N1 as part of the variable name?

If you're on bash, you could do something like:

$ N1=1
$ a1=18
$ varname="a${N1}"
$ f1=${!varname}
$ echo $f1
18
2 Likes

See what happens if N1 had been set using N1='$(echo *)' when you run that eval command.

Then imagine what would happen if a malicious user changed echo to rm -rf when he/she provided the value to set N1.

1 Like