bash 中带有嵌入引号的字符串扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9098797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:27:41  来源:igfitidea点击:

String expansion in bash with embedded quotes

bashshellexpansionsubshell

提问by dreftymac

Problem:

问题:

The following shell script code does not produce the expected result:

以下 shell 脚本代码不会产生预期的结果:

# 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

使用名称创建的新数据库 zztest

Actual outcome:

实际结果:

A new database created with the name $TARG_DB

使用名称创建的新数据库 $TARG_DB

Question:

题:

How can this example code be changed such that $TARG_DBis interpolated or expanded, giving the expected outcome?

如何更改此示例代码以进行$TARG_DB插值或扩展,从而给出预期结果?

回答by Kevin

Because $TARG_DBis within single quotes within the subshell, it's taken literally. Use double quotes there, they won't mess up the subshell. e.g.

因为$TARG_DB在子shell 中的单引号内,它是按字面意思理解的。在那里使用双引号,它们不会弄乱子外壳。例如

$ 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

回答by SiegeX

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");

回答by sgibb

TARG_DB="zztest";
DB_CREATE="$(${MYSQL} -u ${MyUSER} -h ${MyHOST} -p${MyPASS} -Bse \"create database ${TARG_DB}\")";

回答by Mithrandir

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.

'create database $TARG_DB'部分是错的!单引号禁止 bash 中的变量替换。MySQL“看到”文字文本“$TARG_DB”并创建一个具有该名称的数据库。将您的 sql 语句放在双引号中。