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!

Shishir Gupta
  • 121
  • 1
  • 1
  • 5
  • More intuitive, I don't know. Less efficient, certainly. You are preventing name completion. Bash will do completion on the names of environment variables. Try this: execute `export SOME_LONG_VARIABLE_NAME="variable content"`. Then type `echo $SOME_L` and [tab][enter] – xenoid Jul 30 '19 at 09:45
  • 1
    Possible duplicate of [indirect variable expansion in POSIX as done in bash?](https://unix.stackexchange.com/questions/111618/indirect-variable-expansion-in-posix-as-done-in-bash) – l0b0 Jul 30 '19 at 09:52

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
  • 50,672
  • 41
  • 197
  • 360
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,231
  • 2
  • 41
  • 66