bash 壳中的变量插值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17622106/
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
Variable interpolation in the shell
提问by tawheed
I have a variable called filepath=/tmp/name
.
我有一个名为filepath=/tmp/name
.
To access the variable, I know that I can do this: $filepath
要访问变量,我知道我可以这样做: $filepath
In my shell script I attempted to do something like this (the backticks are intended)
在我的 shell 脚本中,我试图做这样的事情(反引号是有意的)
`tail -1 $filepath_newstap.sh`
This line fails, duuh!, because the variable is not called $filepath_newstap.sh
这一行失败了,duuh!,因为变量没有被调用 $filepath_newstap.sh
How do I append _newstap.sh
to the variable name?
如何附加_newstap.sh
到变量名?
Please note that backticks are intended for the expression evaluation.
请注意,反引号用于表达式计算。
回答by choroba
Use
用
"$filepath"_newstap.sh
or
或者
${filepath}_newstap.sh
or
或者
$filepath\_newstap.sh
_
is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap
.
_
是标识符中的有效字符。点不是,所以外壳试图插入$filepath_newstap
.
You can use set -u
to make the shell exit with an error when you reference an undefined variable.
set -u
当您引用未定义的变量时,您可以使用使 shell 退出并显示错误。
回答by tawheed
Use curly braces around the variable name:
在变量名周围使用花括号:
`tail -1 ${filepath}_newstap.sh`
回答by vyom
In Bash:
在 Bash 中:
tail -1 ${filepath}_newstap.sh