16

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?

3 Answers 3

14

With the nullglob option.

$ shopt -s nullglob
$ for i in zzz* ; do echo "$i" ; done
$ 
Sign up to request clarification or add additional context in comments.

2 Comments

your code works for me even without the nullglob option, what am I doing wrong?
@DenisGolomazov: You have files that match. Try using a glob that matches no files.
12
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


Edit, 8 years later (thanks for the comment, @tadman!)

You can avoid the loop altogether with

find . -type f -exec echo "{}" \;

This tells find to echo the name of each file by substituting its name for {}. The escaped semicolon is necessary to terminate the command that's passed to -exec.

3 Comments

find is swiss army knife, true. but used it such a way with for loop is prone to fail upon files with spaces.
Additionally, this will split on the echo $i since you left I unquoted. See this for examples of better syntax.
This won't work if your filenames have spaces in them.
3
for file in MY-FOLDER/MOVIE*
do
  # Skip if not a file
  test -f "$file" || continue
  # Now you know it's a file.
  ...
done

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.