【问题标题】:"ls" works in cmd line but not in script for directories with space in their names“ls”适用于 cmd 行,但不适用于名称中带有空格的目录的脚本
【发布时间】: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/…

标签: linux bash shell ls


【解决方案1】:

您的脚本有两个问题。首先,您没有正确设置VARDIR,因为您有太多反斜杠。其次,您应该在任何变量的任何使用处加上引号。

$ cat test.sh

#!/bin/bash
VARDIR="testfolder/folder01"
ls "$VARDIR"
VARDIR="testfolder/folder01 (copy)"
ls "$VARDIR"

设置 VARDIR 时,您可以使用反斜杠或引号,但不能同时使用

VARDIR="testfolder/folder01 (copy)"

VARDIR=testfolder/folder01\ \(copy\)

【讨论】:

    【解决方案2】:

    试试:

    ls "$VARDIR"
    

    双引号会保留空格,不需要反斜杠。

    【讨论】:

    • VARDIR="testfolder/folder01 (copy)";ls "$VARDIR" 适合我,但无论如何。
    • 谢谢!这行得通!我用了 VARDIR="testfolder/folder01 (copy)" 它解决了这个问题。
    • @yellowantphil 我不知道,我就这么做了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多