2

I am new to Linux, pardon any wrong terminology used here.

I am using Ubuntu 18.04. I am reading text in a shell script using read command. I have a variable in bash window that I want to substitute in that read command. My shell script looks like this:

echo "Enter Text"
read text
echo "Text is $text"

Then I execute it like this in terminal

user@machine:~$ var="hello world"
user@machine:~$ ./script.sh
Enter text
$var
Text is $var
user@machine:~$ 

Notice the line in output - Text is $var.. how can I make it read the value of variable var so it stores hello world in variable named text?

NOTE: I know there is an option to pass parameters to scripts, but I find this more intuitive for the user executing script hence wanted to know how to do it this way!

2 Answers2

4

This is called indirection, and the syntax is ${!reference} to substitute the value of the variable whose name is in the reference variable. For example:

name='Jane Doe'
reference='name'
$ echo "${!reference}"
Jane Doe
l0b0
  • 51,350
0

You need to export your variable first:

export var=test

Then, use envsubst to replace variables inside text:

echo "Enter Text"
read text
printf 'Text is %s\n' "$text" | envsubst

envsubst - substitutes environment variables in shell format strings

pLumo
  • 22,565