Bash script doesn't evaluate variable in filen

2020-04-21 09:06发布

问题:

I have a bash script which creates a backup of my folder. It should name the tar gz file using a version number but it doesn't:

#!/bin/bash

ver='1.2.3'
tar czf $ver_myfolder.tar.gz .

Expected output:

1.2.3_myfolder.tar.gz

Actual output:

_myfolder.tar.gz

If I append the variable like this:

#!/bin/bash

ver='1.2.3'
tar czf myfolder-$ver.tar.gz .

It works

回答1:

You should use ${var} here since you are appending underscore after it which is considered a valid character for variable names. Due to that fact shell doesn't know whether you're expanding variable name $ver or $ver_myfolder:

ver='1.2.3'
tar czf "${ver}_myfolder.tar.gz" .

Since $ver_myfolder is unset, you get an empty value.



回答2:

Because the underscore is a valid character for a variable name, you should use braces to explicitly specify the range of your variable:

${ver}_myfolder.tar.gz
 ^   ^

Without braces, Bash will actually try to parse

${ver_myfolder}.tar.gz

For your edited question, it is because the dot is not a valid character for a variable name, so Bash will not attempt to parse the dot into the name lookup. Even if you put it into braces, a variable name containing a dot is still invalid:

$ echo ${ver.}
bash: ${ver.}: bad substitution
$ ver.=1.2.3
ver.=1.2.3: command not found