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
  • 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
    Commented Jul 30, 2019 at 9:45
  • 1
    Possible duplicate of indirect variable expansion in POSIX as done in bash?
    – l0b0
    Commented Jul 30, 2019 at 9:52

2 Answers 2

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
10
  • 2
    Why the downvote?
    – l0b0
    Commented Jul 30, 2019 at 8:59
  • I did not downvote.. someone else did on both the answers! Commented Jul 30, 2019 at 9:01
  • Also, I changed script.sh last line to echo "Text is $text ${!text}" and it threw an error on execution saying "./script.sh: line 3: $var: bad substitution." Commented Jul 30, 2019 at 9:06
  • Then you're most likely not running Bash. Or you're running pre-4.3.
    – l0b0
    Commented Jul 30, 2019 at 9:08
  • 1
    @Shishir you don't have a shebang in your script, so it's run with sh, not bash
    – muru
    Commented Jul 30, 2019 at 9:13
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

2
  • 2
    Doesn't work. Empty output! Probably since $var is not an environment variable? Commented Jul 30, 2019 at 9:09
  • yes sure ... see my edit
    – pLumo
    Commented Jul 30, 2019 at 9:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .