Linux 在 Bash 中使用下划线“_”无法正确打印文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5898601/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:56:36  来源:igfitidea点击:

Filename not printing correctly with underscore "_" in Bash

linuxbash

提问by Mahakaal

I am using this

我正在使用这个

DATE_FOLDER=$(date +"%b-%d-%a-%G")
FILENAME="HOME_$date1.tar.gz"

echo $BACKUP_DESTINATION/$DATE_FOLDER/$FOLDERNAME_$FILENAME

My output is

我的输出是

home/May-04-Wed-2011/HOME_May-04-0718PM-2011.tar.gz

but if I use -instead of underscore _

但如果我使用 -而不是下划线_

echo $BACKUP_DESTINATION/$DATE_FOLDER/$FOLDERNAME-$FILENAME

then my ouput is correct

那么我的输出是正确的

/home/May-04-Wed-2011/vmware-HOME_May-04-0717PM-2011.tar.gz

Why is that?

这是为什么?

采纳答案by Ignacio Vazquez-Abrams

_is a valid character for a variable name, and $FOLDERNAME_doesn't exist.

_是变量名的有效字符,$FOLDERNAME_不存在。

echo "$BACKUP_DESTINATION/$DATE_FOLDER/${FOLDERNAME}_$FILENAME"

回答by user4471187

The problem is here : HOME_$date1.tar.gzand also here: _$FILENAME. If you use _$then the $is escaped.

问题在这里 :HOME_$date1.tar.gz也在这里: _$FILENAME。如果您使用_$$则转义。

Nevertheless you can do it with: \\_$. Then you escape the _with the \and the $will be interpreted as you are used to it.

不过,您可以使用:\\_$. 然后你_用 the转义 the\并且 the $will 被解释为你习惯了。