String expansion in bash with embedded quotes
Frage
Problem:
The following shell script code does not produce the expected result:
# MYSQL, MyUSER MyHost etc ... all defined above as normal
TARG_DB="zztest";
DB_CREATE="$($MYSQL -u $MyUSER -h $MyHOST -p$MyPASS -Bse 'create database $TARG_DB')";
Expected outcome:
A new database created with the name zztest
Actual outcome:
A new database created with the name $TARG_DB
Question:
How can this example code be changed such that $TARG_DB
is interpolated or expanded, giving the expected outcome?
Lösung
Because $TARG_DB
is within single quotes within the subshell, it's taken literally. Use double quotes there, they won't mess up the subshell. e.g.
$ tmp="a b c"
$ echo $tmp
a b c
$ echo $(echo $tmp)
a b c
$ echo $(echo "$tmp")
a b c
$ echo $(echo '$tmp')
$tmp
$ echo "$(echo '$tmp')"
$tmp
$ echo "$(echo "$tmp")"
a b c
Andere Tipps
Don't wrap it in single-quotes.
There is no need to quote the command substitution $()
so you can remove those and use double-quotes inside it.
DB_CREATE=$($MYSQL -u $MyUSER -h $MyHOST -p$MyPASS -Bse "create database $TARG_DB");
TARG_DB="zztest";
DB_CREATE="$(${MYSQL} -u ${MyUSER} -h ${MyHOST} -p${MyPASS} -Bse \"create database ${TARG_DB}\")";
The 'create database $TARG_DB'
part is wrong! Single quotes supress variable substitution in bash. MySQL "sees" the literal text "$TARG_DB" and creates a database with that name. Put your sql statement in double quotes.