Bash脚本不评估文件名中的变量 [英] Bash script doesn't evaluate variable in filename
问题描述
我有一个bash脚本,可以创建我的文件夹的备份.它应使用版本号命名tar gz文件,但不能:
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 .
预期输出:
1.2.3_myfolder.tar.gz
1.2.3_myfolder.tar.gz
实际输出:
_myfolder.tar.gz
_myfolder.tar.gz
如果我像这样附加变量:
If I append the variable like this:
#!/bin/bash
ver='1.2.3'
tar czf myfolder-$ver.tar.gz .
有效
推荐答案
您应在此处使用${var}
,因为您将在其后附加下划线,该下划线被视为变量名称的有效字符.由于这个事实,shell不知道您是在扩展变量名$ver
还是$ver_myfolder
:
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" .
由于未设置$ver_myfolder
,您将获得一个空值.
Since $ver_myfolder
is unset, you get an empty value.
这篇关于Bash脚本不评估文件名中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!