Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the output of a shell command as a variable [duplicate]

Tags:

bash

shell

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

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

If $1 is var1 echo should print test.

${$1} throws error "bad substitution"

like image 979
Santhosh Kumar Avatar asked Oct 20 '22 20:10

Santhosh Kumar


1 Answers

What you want is called variable expansion (or indirect expansion). You have to 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 value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character which is not to be interpreted as part of its name.

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

like image 168
fredtantini Avatar answered Oct 22 '22 19:10

fredtantini