How to iterate over files in a directory with Bash?



Answers

Sorry for necromancing the thread, but whenever you iterate over files by globbing, it's good practice to avoid the corner case where the glob does not match (which makes the loop variable expand to the (un-matching) glob pattern string itself).

For example:

for file in Data/*.txt; do
    [ -e "$file" ] || continue
    # ... rest of the loop body
done

Reference: Bash Pitfalls

Question

I need to write a script that starts my program with different arguments, but I'm new to Bash. I start my program like this:

./MyProgram.exe Data/data1.txt [Logs/data1_Log.txt].

Here is the pseudocode for what i want to do:

for each filename in /Data do
  for int i = 0, i = 3, i++
    ./MyProgram.exe Data/filename.txt Logs/filename_Log{i}.txt
  end if
end for

So I'm really puzzled how to create second argument from the first one, so it looks like dataABCD_Log1.txt and start my program. Help is very much appreciated.

P.S. I know there are simililar questions out there, but I found nothing on creating my logfile name.




Something I use to avoid having extra lines or checks:

#!/bin/bash
for filename in $(find /Data/*.txt 2> /dev/null); do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

The idea is run the find in a subshell and send errors to /dev/null, so that you never loop over an error about missing files.






Related