Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

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
...
like image 320
mbergmann Avatar asked Dec 18 '22 02:12

mbergmann


2 Answers

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
like image 123
tripleee Avatar answered Jan 21 '23 15:01

tripleee


You can create an array with the files, then remove and keep the first element from this array, process it separately and then process the remaining elements of the array:

# create array with files
files=(/path/to/files/*)

# get the 1st element of the array
first=${files[0]}

# remove the 1st element of from array
files=("${files[@]:1}")

# process the 1st element
echo First run: "$first"

# process the remaining elements
for file in "${files[@]}"; do
   echo "$file"
done
like image 31
ネロク・ゴ Avatar answered Jan 21 '23 15:01

ネロク・ゴ