Example
for FILE in $DIR/* do if(<is last File>) doSomethingSpecial($FILE) else doSomethingRegular($FILE) fi done
What to call for <is last file>
to check if the current file is the last one in the array ?
Is there an easy built-in check without checking the array's length by myself ?
What to call for to check if the current file is the last one in the array ?
For a start, you are not using an array. If you were then it would be easy:
declare -a files files=($DIR/*) pos=$(( ${#files[*]} - 1 )) last=${files[$pos]} for FILE in "${files[@]}" do if [[ $FILE == $last ]] then echo "$FILE is the last" break else echo "$FILE" fi done
I know of no way to tell that you are processing the last element of a list in a for loop. However you could use an array, iterate over all but the last element, and then process the last element outside the loop:
files=($DIR/*) for file in "${files[@]::${#files[@]}-1}" ; do doSomethingRegular "$file" done doSomethingSpecial "${files[@]: -1:1}"
The expansion ${files[@]:offset:length}
evaluates to all the elements starting at offset
(or the beginning if empty) for length
elements. ${#files[@]}-1
is the number of elements in the array minus 1.
${files[@]: -1:1}
evaluates to the last element - -1 from the end, length 1. The space is necessary as :-
is treated differently to : -
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With