Use shell command output as a variable

I want to use the output of the echo command as the name of a variable. How,

var1="test" var2="script" echo ${$1} 

If $1 is var1, the echo should print a test.

${$1} throws a bad replacement error

+5
source share
2 answers

What you want is called a variable extension (or indirect extension). You should use the syntax ${!var} :

 ~$ cat s.sh var1="test" var2="script" echo ${!1} ~$ ./s.sh var1 test ~$ ./s.sh var2 script 

From man bash :

${parameter}

The parameter value is replaced. Brackets are necessary when a parameter is a positional parameter with more than one digit, or when a parameter is followed by a character that should not be interpreted as part of its name.

If the first character of the parameter is an exclamation mark (!), The level of the indirectness variable is entered. Bash uses the value of a variable formed from the rest of the parameter as the name of the variable; this variable is then expanded and this value is used in the rest of the substitution, not the value of the parameter itself. This is called an indirect extension. The exception is the extension $ {! Prefix *} and $ {! Name [@]} described below. The exclamation point must immediately follow the left bracket to introduce indirection.

+3
source

You can do it:

 $ foo='bar' $ baz='foo' $ echo ${!baz} bar 
0
source

Source: https://habr.com/ru/post/1209252/


All Articles