在 Bash 中循环使用空格的目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4895484/
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
Loop over directories with whitespace in Bash
提问by jakev
In a bash script, I want to iterate over all the directories in the present working directory and do stuff to them. They may contain special symbols, especially whitespace. How can I do that? I have:
在 bash 脚本中,我想遍历当前工作目录中的所有目录并对它们执行操作。它们可能包含特殊符号,尤其是空格。我怎样才能做到这一点?我有:
for dir in $( ls -l ./)
do
if [ -d ./"$dir" ]
but this skips my directories with whitespace in their name. Any help is appreciated.
但这会跳过我的名称中带有空格的目录。任何帮助表示赞赏。
回答by Paused until further notice.
Give this a try:
试试这个:
for dir in */
回答by SpliFF
Take your pick of solutions:
选择解决方案:
http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
The general idea is to change the default seperator (IFS).
一般的想法是更改默认分隔符 (IFS)。
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *
do
echo "$f"
done
IFS=$SAVEIFS
回答by yankee
There are multiple ways. Here is something that is very fast:
有多种方式。这是非常快的事情:
find /your/dir -type d -print0 | xargs -0 echo
This will scan /your/dir recursively for directories and will pass all paths to the command "echo" (exchange to your need). It may call echo multiple time, but it will try to pass as many directory names as the console allows at once. This is extremely fast because few processes need to be started. But it works only on programs that can take an arbitrary amount of values as options. -print0 tells find to seperate file paths using a zero byte (and -0 tells xargs to read arguments seperated by zero byte) If you don't have the later one, you can do this:
这将递归扫描 /your/dir 目录并将所有路径传递给命令“echo”(根据您的需要进行交换)。它可能会多次调用 echo,但它会尝试一次传递控制台允许的尽可能多的目录名称。这非常快,因为需要启动的进程很少。但它仅适用于可以将任意数量的值作为选项的程序。-print0 告诉 find 使用零字节分隔文件路径(并且 -0 告诉 xargs 读取由零字节分隔的参数)如果你没有后一个,你可以这样做:
find /your/dir -type d -print0 | xargs -0 -n 1 echo
or
或者
find /your/dir -type d -print0 --exec echo '{}' ';'
The option -n 1 will tell xargs not to pass more arguments than one at the same time to your program. If you don't want find to scan recursively you can specify the depth option to disable recursion (don't know the syntax by heart though).
选项 -n 1 将告诉 xargs 不要同时向您的程序传递多于一个的参数。如果你不想 find 递归扫描,你可以指定深度选项来禁用递归(虽然不知道语法)。
Though if that's usable in your particular script is another question ;-).
尽管这是否可用于您的特定脚本是另一个问题;-)。

