我有一个变量名为filepath=/tmp/name
。
要访问该变量,我知道可以这样做:$filepath
在我的shell脚本中,我尝试像这样做(反引号是有意义的)
`tail -1 $filepath_newstap.sh`
这条命令失败了,因为变量没被叫做$filepath_newstap.sh
。
我该如何将_newstap.sh
附加到变量名上?
请注意反引号是用于表达式求值的。
使用
"$filepath"_newstap.sh
或者${filepath}_newstap.sh
或者$filepath\_newstap.sh
_
是标识符中的有效字符。点不是,因此shell尝试插入$filepath_newstap
。
您可以使用set -u
使shell在引用未定义变量时退出并显示错误信息。
在变量名周围使用花括号:
`tail -1 ${filepath}_newstap.sh`
"$filepath"_foo
和${filepath}_foo
都会扩展为/tmp/name_foo
。然而,'$filepath'_foo
、"$"filepath_foo
和$"filepath"_foo
都可以完全避免扩展。这就是为什么export PATH=$PATH:$addpath
的操作能将:$addpath
(可能会受到参数扩展的影响)添加到PATH
环境变量中的原因。 - user539810在Bash中:
tail -1 ${filepath}_newstap.sh
set -u
,如果您引用了未定义的变量,它会导致脚本中止。 - tripleee${}
和双引号之间有什么区别?我应该更喜欢哪一个? - user31389