Bash scripting, loop through files in folder fails

I'm looping through certain files (all files starting with MOVIE) in a folder with this bash script code:

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*.

How can I avoid it to enter the things after

do

if there aren't any files in the folder?


for i in $(find MY-FOLDER/MOVIE -type f); do
  echo $i
done

The find utility 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.

-type f will find only regular files (not directories).

As I wrote it, the command will find files in subdirectories as well; you can prevent that by adding -maxdepth 1


使用nullglob选项。

$ shopt -s nullglob
$ for i in zzz* ; do echo "$i" ; done
$ 

for file in MY-FOLDER/MOVIE*
do
  # Skip if not a file
  test -f "$file" || continue
  # Now you know it's a file.
  ...
done
链接地址: http://www.djcxy.com/p/17488.html

上一篇: 如何检查给定路径中是​​否存在目录

下一篇: Bash脚本,循环浏览文件夹中的文件失败