jomobro jomobro - 11 days ago 7
Bash Question

Bash for loop on directories

I have a bash script that I'd like to run a program in one directory, using a file from another directory as input

There are several input files, located in several different directories, each of which is used as input for one iteration of the program

The files are one filetype (.foo) of several in each of these directories

My code is

cd /path/to/data/
for D in *; do
# command 1
if [ -d "$D" ]
then
cd /path/to/data
# command 2
for i in *.foo
do
# command 3
done
fi
done


When I run the script, the output is as follows

# command 1 output
# command 2 output
# command 3 output
# command 2 output
# command 2 output
# command 2 output
# command 2 output
# command 2 output
.
.
.


So the script does what I expect it to do exactly once, and then seems to not iterate over the final for loop after that

Why is this?

Answer

I think you have a typo error after "then"... It makes more sense to be:

then
  cd /path/to/data/$D
  # command 2

But as advised by cdarke, it is good to avoid to use cd in your script. You can have the same result like this:

for D in /path/to/data; do
    # command 1
    if [ -d "$D" ]
    then
        # command 2
        for i in /path/to/data/$D/*.foo
        do
            # command 3
        done
    fi
done

Or you could even use find and avoid the if parts (less code makes faster your script):

for D in $(find /path/to/data -maxdepth 1 -type d)
# -type d in find get's only directories
# -maxdepth 1 means current dir. If you remove maxdepth option all subdirs will be found. 
# OR you can increase -maxdepth value to control how deep you want to search inside sub directories.