Tony
Tony

Reputation: 1403

How to expand a variable "read" from terminal

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'

Upvotes: 1

Views: 193

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 126038

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.

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30665

check this

 eval "echo $_test"

or

bash -c "echo $_test"

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

Upvotes: 1

Related Questions