【发布时间】:2015-01-28 19:28:01
【问题描述】:
我是 bash 脚本的初学者,我正在尝试编写一个脚本,该脚本具有变量目录名称,并且谁使用这些变量值来运行简单的 bash 命令,例如“ls”和“cd”。例如,当目录具有“普通”名称时,它可以正常工作
testfolder/folder01
但是当目录名称中包含空格和括号时会失败,例如,当您复制子目录并粘贴到包含子目录的同一目录中时会发生这种情况。在这个脚本中可以看到问题:
[boblacerda@localhost MyScripts]$ cat test.sh
#!/bin/bash
VARDIR="testfolder/folder01"
ls $VARDIR
VARDIR="testfolder/folder01\ \(copy\)"
ls $VARDIR
[boblacerda@localhost MyScripts]$
这是调试模式下脚本的输出:
[boblacerda@localhost MyScripts]$ bash -x test.sh
+ VARDIR=testfolder/folder01
+ ls testfolder/folder01
testefile01 testefile02
+ VARDIR='testfolder/folder01\ \(copy\)'
+ ls 'testfolder/folder01\' '\(copy\)'
ls: cannot access testfolder/folder01\: No such file or directory
ls: cannot access \(copy\): No such file or directory
+ exit
[boblacerda@localhost MyScripts]$
如您所见,使用具有“正常”名称的目录的第一部分有效,但使用名称中包含空格和括号的目录的第二部分失败。如果我在 ls 命令中引用 VARDIR,问题仍然存在,即,如果我像这样使用 ls
ls "$VARDIR"
这种情况下的输出是这样的:
[boblacerda@localhost MyScripts]$ bash -x test.sh
+ VARDIR=testfolder/folder01
+ ls testfolder/folder01
testefile01 testefile02
+ VARDIR='testfolder/folder01\ \(copy\)'
+ ls 'testfolder/folder01\ \(copy\)'
ls: cannot access testfolder/folder01\ \(copy\): No such file or directory
+ exit
[boblacerda@localhost MyScripts]$
最后要添加的命令
ls testfolder/folder01\ \(copy\)
在 cmd 中可以正常工作,如下所示:
[boblacerda@localhost MyScripts]$ls testfolder/folder01\ \(copy\)
testefile01 testefile02
[boblacerda@localhost MyScripts]$
感谢大家的关注。
【问题讨论】:
-
脚本中的引号过多。我相信命令行中的
ls "testfolder/folder01\ \(copy\)"也会失败。转义空格 或 引用字符串。 -
为什么是反斜杠?
-
您可以尝试在脚本中设置
IFS=$'\n'。然后它只会在文件名中有换行符时才会中断。如果你的文件名有换行符,你可以试试find -print0。 -
另外,查看使用单引号字符和双引号字符之间的区别。当你单引号时,事情不会以与双引号相同的方式展开。我知道双引号解决了您的问题,但了解原因很重要。这是一个体面的总结。 howtogeek.com/howto/29980/…