Ale*_*lls 8 shell-script syntax
这个问题想了很久,还是不知道怎么查
这是:
x=`command -v r2g`
Run Code Online (Sandbox Code Playgroud)
与此相同:
x="$(command -v r2g)"
Run Code Online (Sandbox Code Playgroud)
还是和这个一样:
x=$(command -v r2g)
Run Code Online (Sandbox Code Playgroud)
...如果是后者,我应该这样做来修复它吗?
x="`command -v r2g`"
Run Code Online (Sandbox Code Playgroud)
所有示例都是命令替换中的变量赋值,因此它们是等效的。根据Gilles 的回答,在赋值给变量的右手边不需要引用,因为那里不会发生分词。因此,所有四个都OK。
如果它们是独立的,即不在分配中,那么您需要引用。$(...)
与反引号相比,这种 形式的优点是引号可以嵌套并分成多行,这就是为什么现在这种形式普遍受欢迎的原因。换句话说,您可以"$( echo "$var" )"
使用这种形式来保护 的内部扩展$var
和外部扩展$(...)
免受分词和文件名通配。
如POSIX Shell 命令语言规范中所示,嵌入式多行脚本不适用于反引号(左侧),但适用于$()
表单(右侧)。
echo ` echo $(
cat <<\eof cat <<\eof
a here-doc with ` a here-doc with )
eof eof
` )
echo ` echo $(
echo abc # a comment with ` echo abc # a comment with )
` )
echo ` echo $(
echo '`' echo ')'
` )
Run Code Online (Sandbox Code Playgroud)