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!

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

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
  • 1
    Why the downvote? – l0b0 Jul 30 at 8:59
  • I did not downvote.. someone else did on both the answers! – Shishir Gupta Jul 30 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." – Shishir Gupta Jul 30 at 9:06
  • Then you're most likely not running Bash. Or you're running pre-4.3. – l0b0 Jul 30 at 9:08
  • 1
    @Shishir you don't have a shebang in your script, so it's run with sh, not bash – muru Jul 30 at 9:13
-1

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
    Doesn't work. Empty output! Probably since $var is not an environment variable? – Shishir Gupta Jul 30 at 9:09
  • yes sure ... see my edit – pLumo Jul 30 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.