current through loop How to iterate over files in a directory with Bash?

2 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 filename in Data/*.txt; do
    [ -e "$filename" ] || continue
    # ... rest of the loop body

Reference: Bash Pitfalls

bash loop through files in directory recursively

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:

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"

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.