Bash 脚本,遍历文件夹中的文件失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7477543/
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
Bash scripting, loop through files in folder fails
提问by user809829
I'm looping through certain files (all files starting with MOVIE) in a folder with this bash script code:
我正在使用此 bash 脚本代码循环浏览文件夹中的某些文件(所有以 MOVIE 开头的文件):
for i in MY-FOLDER/MOVIE*
do
which works fine when there are files in the folder. But when there aren't any, it somehow goes on with one file which it thinks is named MY-FOLDER/MOVIE*.
当文件夹中有文件时,它工作正常。但是当没有任何文件时,它会以某种方式继续处理一个它认为名为 MY-FOLDER/MOVIE* 的文件。
How can I avoid it to enter the things after
我怎样才能避免它进入后的东西
do
if there aren't any files in the folder?
如果文件夹中没有任何文件?
采纳答案by Adam Liss
for i in $(find MY-FOLDER/MOVIE -type f); do
echo $i
done
The findutility is one of the Swiss Army knives of linux. It starts at the directory you give it and finds all files in all subdirectories, according to the options you give it.
该find实用程序是 linux 的瑞士军刀之一。它从您提供的目录开始,并根据您提供的选项查找所有子目录中的所有文件。
-type fwill find only regular files (not directories).
-type f只会找到常规文件(而不是目录)。
As I wrote it, the command will find files in subdirectories as well; you can prevent that by adding -maxdepth 1
正如我写的那样,该命令也会在子目录中查找文件;你可以通过添加来防止这种情况-maxdepth 1
Edit, 8 years later (thanks for the comment, @tadman!)
8 年后编辑(感谢评论,@tadman!)
You can avoid the loop altogether with
你可以完全避免循环
find . -type f -exec echo "{}" \;
This tells findto echothe name of each file by substituting its name for {}. The escaped semicolon is necessary to terminate the command that's passed to -exec.
这find通过echo将名称替换为每个文件的名称来告知每个文件的名称{}。转义分号是终止传递给 的命令所必需的-exec。
回答by Ignacio Vazquez-Abrams
With the nullgloboption.
随着nullglob选项。
$ shopt -s nullglob
$ for i in zzz* ; do echo "$i" ; done
$
回答by Idelic
for file in MY-FOLDER/MOVIE* do # Skip if not a file test -f "$file" || continue # Now you know it's a file. ... done

