variable interpolation in shell

2020-01-27 03:40发布

This is probably a very basic question but for some reason I seem to be over looking the obvious.

I have a variable called filepath=/tmp/name

To access the variable I know that I can do this $filepath

In my shell script I attempted to do something like this (The back ticks are intended)

`tail -1 $filepath_newstap.sh`

This line fails, duuh! because the variable is not called $filepath_newstap.sh

How do I append _newstap.sh to the variable name? Please note that back ticks are intended for the expression evaluation

标签: bash shell unix
3条回答
够拽才男人
2楼-- · 2020-01-27 03:49

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.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

查看更多
Evening l夕情丶
3楼-- · 2020-01-27 03:55

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`
查看更多
在下西门庆
4楼-- · 2020-01-27 04:04

In bash:

tail -1 ${filepath}_newstap.sh
查看更多
登录 后发表回答