触摸字符串中转义感叹号

时间:2018-11-25 17:17:25

标签: string bash escaping

每次下载youtube文件(例如abc.mp4)时,我都会通过在bash终端中手动执行以下命令来立即更改其日期/时间戳:touch -d "$(date)" "abc.mp4"

如果文件具有嵌入的感叹号(例如ab!c.mp4),则例外效果很好。然后,以下命令发生故障:touch -d "$(date)" "ab!c.mp4"

实验中,我尝试:touch -d "$(date)" "ab\!c.mp4"不高兴,touch命令创建了一个新的空文件,名称为ab\!c.mp4

我的 kludgy 解决方案是手动重命名youtube文件,从其名称中删除感叹号,然后执行touch命令。

是否有一种更优雅的方法可以将感叹号保留在文件名中?

2 个答案:

答案 0 :(得分:2)

尝试在set +H命令之前调用touch,或仅使用单引号:touch -d "$(date)" 'ab!c.mp4'

答案 1 :(得分:2)

关闭历史记录扩展(设置+ H)或使用单引号。例如:

$ echo "foo!bar"
bash: !bar": event not found
$ echo 'foo!bar'
foo!bar
$ set +H
$ echo "foo!bar"
foo!bar

从联机帮助页:

Only backslash (\) and single quotes can quote the history expansion character.

此外,供参考:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.  The characters $ and ` retain their special meaning within double quotes.  The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \,  or <newline>.   A  double  quote  may  be quoted within double quotes by preceding it with a backslash.  If enabled, history expansion will be performed unless an !  appearing in double quotes is escaped using a backslash.  The backslash  preceding the !  is not removed.