简体   繁体   English

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

[英]Shell script issue with filenames containing spaces

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”却不起作用,唯一的区别是用“ ls”替换了“ echo”?

echo.sh 回声

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

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

But, "ls.sh" fails: 但是,“ ls.sh”失败:

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

Produces : 产生
ls: cannot access 'ab c': No such file or directory ls:无法访问“ ab c”:没有此类文件或目录
ls: cannot access 'de f': No such file or directory ls:无法访问“ de f”:没有此类文件或目录
ls: cannot access 'echo.sh': No such file or directory ls:无法访问“ echo.sh”:没有这样的文件或目录
ls: cannot access 'ls.sh': No such file or directory ls:无法访问“ ls.sh”:没有这样的文件或目录

you're actually adding redundant "'" (which your echo invocation shows) 您实际上是在添加多余的“'”(回声调用将显示该内容)

try this: 尝试这个:

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

change the following line from 将以下行从

ls "'$f'"

into 进入

ls "$f"

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 ls ls will try to look up a file named 'file-1' instead of file-1 and a file with such a name just doesn't exist. 将它们与ls一起使用ls将尝试查找名为'file-1'而不是file-1的文件,并且这样名称的文件不存在。

In your example you just added one pair of ' s too much. 在您的例子,你刚才添加1对'太过分了。 A single pair of double quotes " is enough to take care of spaces that might contained in the file names: 一对双引号"足以处理文件名中可能包含的空格:

#!/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 $f like this: 您试图避免的问题只会在您不使用$f这样的双引号的情况下出现:

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

What about this ? 那这个呢 ? =) =)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM