문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top