Error assigning bash to special variables

Question: Question:

When the following sample.sh is run with bash, an error is thrown with a special variable to which a variable is assigned.
Probably because it is treated as a character string, I think that it is not pulling the argument, but is there any countermeasure?

[root@ test]# cat sample.sh
#!/bin/bash

echo $2

echo ${2}

N=2
echo ${$N}

[root@ test]# sh sample.sh a b c
b
b
sample.sh: 行 8: ${$N}: 誤った代入です

Answer:

#!/bin/bash

echo $2

echo ${2}

N=2
echo ${!N}

By

 % ./sample.sh foo bar
bar
bar
bar

Can be realized.

Scroll to Top