bash 对于目录中的文件,忽略文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9011458/
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
For files in directory, ignoring folders
提问by Mechaflash
Iterating a for loop, how do I make sure it ignores outputting directories?
迭代 for 循环,如何确保它忽略输出目录?
for filename in /home/user/*
do
echo $filename
done;
回答by Kevin
for filename in /home/user/*
do
if [ ! -d "$filename" ]; then
echo $filename
fi
done
Or, use the findcommand:
或者,使用以下find命令:
find /home/user ! -type d -maxdepth 1
回答by SiegeX
As in my previous answeryou really want to use find. What you're trying to do on 7-10 of lines scripting can just be done with this:
就像我之前的回答一样,您确实想使用find. 您在 7-10 行脚本中尝试执行的操作可以通过以下方式完成:
find /home/user -type f -printf "%f\n"
回答by Adam Zalcman
You can use -doperator to check whether $filenamerefers to a directory:
您可以使用-d运算符检查是否$filename引用目录:
for filename in /home/user/*
do
if [ ! -d "${filename}" ]
then
echo $filename
fi
done;
See test manpagefor details and other available operators.
有关详细信息和其他可用运算符,请参阅测试联机帮助页。
You can also use the find command:
您还可以使用find 命令:
find /home/user -not -type d -maxdepth 1
回答by Abhijeet Rastogi
find command is more suitable for what you want.
find 命令更适合你想要的。
find /home/user -type f
回答by jaypal singh
while IFS='$\n' read -r filename
do echo "$filename"
done < <(find /home/user/ -type f -maxdepth 1)
回答by Dan Fego
You can use a conditional statement inside the loop. Something like this (untested):
您可以在循环内使用条件语句。像这样的东西(未经测试):
if [ ! -d "$filename" ]
then
// do stuff
fi
-dis true if it's a directory, and that's inverted with !. So it will succeed if it does exist and isn't a directory.
-d如果它是一个目录,则为真,并且与!. 因此,如果它确实存在并且不是目录,它将成功。

