Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if file in a loop is the last one?

Tags:

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 ?

like image 423
John Threepwood Avatar asked Sep 06 '12 10:09

John Threepwood


2 Answers

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  
like image 122
cdarke Avatar answered Oct 13 '22 20:10

cdarke


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 : -.

like image 27
camh Avatar answered Oct 13 '22 20:10

camh