Shell – Linux shell script: Allow user to provide variable names in input prompt

shell-script

I'm writing a shell-script for linux terminal. I want to be able to input variable names on a prompt. For example:

test.sh:

 test="Monkey in the middle..."
 read -p "Enter input: " input
 echo $input

output:

 Enter input: $test
 $test

I want to be able to input "$test" during the read -p prompt segment of the script and have the script echo "Monkey in the middle…" at the end instead of echo-ing "$test" as it does now.

How would I go about doing that?



UPDATE:

Using the answers provided to me here and in this thread (a big thanks to the contributors and commentators!), I managed to piece together this line which worked very well for me:

newvariable="$(eval echo $input)" 

Be, advised, I was warned more than once that using eval may pose a security risk. Keep that in mind if you opt for this solution.

Best Answer

Instead of

echo "$input"

try

eval echo "$input"

It's not even bash-specific, works on /bin/sh!

Note that this poses a serious security risk because eval just executes what you give it. In this case, the shell interprets the string $input as $test, and then eval executes echo $test. But what if the user entered $test; rm -rf *? eval would be presented with echo $test; rm -rf *. Be very careful if you do this.

Related Question