问题:单引号在双引号内不符合语法
当你有"'$0'"
,只有那些外部引号是语法的(并控制 shell 如何扩展值:内部引号只是文字值,并且不改变如何扩展值)$0
被治疗。
字面答案(仅限 bash):$''
如果您不希望遵循扩展,请不要使用双引号。
# assign the directory separately, just to make the line shorter for easier reading
dir=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/
# now, expand the directory name in double quotes, but use the $'' quoting style otherwise
assignssid="$dir"$'airport -I | awk \'/ SSID/ {print substr($0, index($0, $2))}\''
Inside $''
, \'
是一个单引号(同样,\n
是一个换行符,\t
是一个选项卡等),并且不会发生参数扩展($'$0'
是相同的'$0'
, not "$0"
).
完成此操作后,您可以看到echo
ing 变量会发出完整的单引号内容的命令:
$ echo "$assignssid"
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'
...或者,与您可能预期的用例更密切相关:
current_ssid=$(eval "$assignssid")
字面答案(POSIX sh):'"'"'
让我们以这样的方式做第一个答案isn't仅 bash:
dir=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/
assignssid="$dir"'airport -I | awk '"'"'/ SSID/ {print substr($0, index($0, $2))}'"'"''
该字符串的作用如下:
- 首先
'
关闭单引号上下文
- 首先
"
打开双引号上下文
- 下列
'
是字面意思,因此成为你的价值的一部分
- 下列
"
关闭双引号上下文
- 决赛
'
恢复原始的单引号上下文
最佳实践答案:使用函数存储代码
字符串变量根本不适合这项工作。相反,使用一个函数:
airport_dir=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/
assignssid() {
"$airport_dir"/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'
}
...此后:
current_ssid=$(assignssid)