1

For example,

create a bash tmp.sh script with the following,

export tmp=abc
read _test
echo "$_test"

Execute bash tmp.sh

Input '$tmp/def'.

Expected result: 'abc/def'

Actual result: '$tmp/def'

Tony
  • 1,225
  • 3
  • 12
  • 26
  • 1
    Why should the user of the script know there *is* a variable `tmp` to expand? – chepner May 03 '20 at 17:29
  • This is an oversimplified example. The case is that tmp is an environment variable to a directory and the user knows that. And they have to input a path to a subdirectory into the variable, say '_test' here, using $tmp/xxx, and then the script knows the path to the subdirectory. – Tony May 03 '20 at 17:43

2 Answers2

1

check this

 eval "echo $_test"

or

bash -c "echo $_test"

Edit Latter (bash -c) uses sub-shell which is safe in comparison with eval

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • 1
    Obligatory: [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/q/17529220/4518341) - also applies to executing input. – wjandrea May 03 '20 at 17:32
  • Thanks! I have a further problem. Suppose tmp is a directory, and _test is a subdir in that directory, then echo $(bash -c "$_test"), then it gives a "bash: xxx: is a directory" – Tony May 03 '20 at 17:38
  • 1
    Thanks again! so I can use something like `_test=$(bash -c "echo $_test")` to update it back to the `_test` variable? – Tony May 03 '20 at 17:53
  • 2
    I wouldn't consider `bash -c` much safer than `eval` -- they both have the same basic risk of treating things you thought were just inert pieces of data as executable code. Executing things you didn't think were commands in a subshell isn't much safer than executing them in the main shell. – Gordon Davisson May 03 '20 at 17:57
0

You can use the envsubst command to substitute environment variables like this:

echo "$_test" | envsubst

or, since this is in bash:

envsubst <<<"$_test"

This is significantly safer than either eval or bash -c, since it won't do anything other than replacing instances of $var or ${var} with the corresponding variable values.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151