bash 文件名包含空格的 Shell 脚本问题

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

Shell script issue with filenames containing spaces

linuxbashshellcommand-linefilenames

提问by tgoneil

I understand that one technique for dealing with spaces in filenames is to enclose the file name with single quotes: "'".

我知道处理文件名中的空格的一种技术是用单引号将文件名括起来:“'”。

Why is it that the following code called, "echo.sh" works on a directory containing filenames with spaces, but the program "ls.sh" does Not work, where the only difference is 'echo' replaced with 'ls'?

为什么以下称为“echo.sh”的代码适用于包含带空格的文件名的目录,但程序“ls.sh”不起作用,唯一的区别是将“echo”替换为“ls”?

echo.sh

回声文件

#!/bin/sh
for f in *
do
echo "'$f'"
done

Produces:
'a b c'
'd e f'
'echo.sh'
'ls.sh'

产生
'abc'
'def'
'echo.sh'
'ls.sh'

But, "ls.sh" fails:

但是,“ls.sh”失败了:

#!/bin/sh
for f in *
do
ls "'$f'"
done

Produces:
ls: cannot access 'a b c': No such file or directory
ls: cannot access 'd e f': No such file or directory
ls: cannot access 'echo.sh': No such file or directory
ls: cannot access 'ls.sh': No such file or directory

产生
ls:无法访问'ab c':没有 那个文件或目录
ls:无法访问'de f':没有
那个文件或目录ls:无法访问'echo.sh':没有那个文件或目录
ls:无法访问' ls.sh': 没有那个文件或目录

回答by Stefano Crespi

you're actually adding redundant "'" (which your echo invocation shows)

你实际上是在添加多余的“'”(你的回声调用显示)

try this:

尝试这个:

#!/bin/sh
for f in *
do
ls "$f"
done

回答by Fredrik Pihl

change the following line from

更改以下行

ls "'$f'"

into

进入

ls "$f"

回答by mikyra

Taking a closer look at the output of your echo.sh script you might notice the result is probably not quite the one you expected as every line printed is surrounded by 'characters like:

仔细查看 echo.sh 脚本的输出,您可能会注意到结果可能与您预期的不太一样,因为打印的每一行都被如下'字符包围:

'file-1'
'file-2'

and so on.

等等。

Files with that names really don't exist on your system. Using them with lsls will try to look up a file named 'file-1'instead of file-1and a file with such a name just doesn't exist.

您的系统上确实不存在具有该名称的文件。将它们与lsls一起使用将尝试查找名为'file-1'而不是的file-1文件,而具有此类名称的文件不存在。

In your example you just added one pair of 's too much. A single pair of double quotes"is enough to take care of spaces that might contained in the file names:

在您的示例中,您只是'过多地添加了一对s。一对双引号"足以处理文件名中可能包含的空格:

#!/bin/sh
for f in *
do
  ls "$f"
done

Will work pretty fine even with file names containing spaces. The problem you are trying to avoid would only arise if you didn't use the double quotes around $flike this:

即使文件名包含空格也能正常工作。只有当您没有$f像这样使用双引号时,才会出现您试图避免的问题:

#!/bin/sh
for f in *
do
  ls $f # you might get into trouble here
done

回答by Gilles Quenot

What about this ? =)

那这个呢 ?=)

#!/bin/sh
for f in *; do
    printf -- '%s\n' "$f"
done