john mark
john mark

Reputation: 9

how to make the variable take place

I have this code in shell script

id='this'
sql="hello $id"
echo "$sql"
id="salut"
echo "$sql"

it will echo

hello this

hello this

how can I get

hello this

hello salut

in other words how can I make the variable id take place when changed inside other variables ?

Upvotes: 0

Views: 40

Answers (2)

rools
rools

Reputation: 1675

You can use eval but it can be risky (depending on what can be inside your variable).

id='this'
sql="hello \$id"
eval "echo $sql"
id='salut'
eval "echo $sql"

A good and safe way to do that is to use a function to reset your sql variable.

prepare_sql() {
    sql="hello $id"
}

id='this'
prepare_sql
echo $sql
id='salut'
prepare_sql
echo $sql

You can even put the assignment in the function.

change_id() {
    id=$1
    sql="hello $id"
}

change_id this
echo $sql
change_id salut
echo $sql

Upvotes: 1

Nic3500
Nic3500

Reputation: 8591

The value of variables is set at the moment you reference them. So for what you want, you have to do:

id='this'
sql="hello $id"     # here, $id == this, so sql == "hello this"
echo "$sql"
id="salut"
sql="hello $id"     # here, $id == salut, so sql == "hello salut"
echo "$sql"

Variables are not re-evaluated when you change them, unless you expressly ask for it.

Upvotes: 0

Related Questions