外壳中的变量插值 [英] Variable interpolation in the shell
问题描述
我有一个名为filepath=/tmp/name
的变量.
要访问该变量,我知道我可以这样做:$filepath
To access the variable, I know that I can do this: $filepath
在我的shell脚本中,我试图做这样的事情(需要使用反引号)
In my shell script I attempted to do something like this (the backticks are intended)
`tail -1 $filepath_newstap.sh`
此行失败,duuh !,因为该变量未称为$filepath_newstap.sh
This line fails, duuh!, because the variable is not called $filepath_newstap.sh
如何在变量名后附加_newstap.sh
?
请注意,反引号用于表达评估.
Please note that backticks are intended for the expression evaluation.
推荐答案
使用
"$filepath"_newstap.sh
或
${filepath}_newstap.sh
或
$filepath\_newstap.sh
_
是标识符中的有效字符.点不是,因此外壳程序尝试对$filepath_newstap
进行插值.
_
is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap
.
当您引用未定义的变量时,可以使用set -u
使shell退出并出现错误.
You can use set -u
to make the shell exit with an error when you reference an undefined variable.
这篇关于外壳中的变量插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!