Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting, loop through files in folder fails

Tags:

bash

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?

like image 604
user809829 Avatar asked Sep 19 '11 21:09

user809829


People also ask

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do you loop a directory in Linux?

We use a standard wildcard glob pattern '*' which matches all files. By adding a '/' afterward, we'll match only directories. Then, we assign each directory to the value of a variable dir. In our simple example, we then execute the echo command between do and done to simply output the value of the variable dir.


1 Answers

With the nullglob option.

$ shopt -s nullglob
$ for i in zzz* ; do echo "$i" ; done
$ 
like image 134
Ignacio Vazquez-Abrams Avatar answered Oct 19 '22 00:10

Ignacio Vazquez-Abrams