Search code examples
linuxbash

How to do a specific action on the first iteration of a while loop in a bash script


I need to make a script do a specific action on first loop iteration.

for file in /path/to/files/*; do
    echo "${file}"
done

I want this output:

First run: file1
file2
file3
file4
...

Solution

  • A very common arrangement is to change a variable inside the loop.

    noise='First run: '
    for file in /path/to/files/*; do
        echo "$noise$file"
        noise=''
    done
    

    Here's a variation using a parameter expansion:

    first="trve"
    for file in /path/to/files/*; do
        echo "${first:+First run: }$file"
        first=""
    done
    

    The expression ${variable:+value} expands to value if $variable is nonempty, and otherwise nothing.