Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I determine the last line of "while read line"?

for example:

    while read line; do
       if [ "$line" = "last line" ]; then
           echo "this line is the last one ($line);"
       else
           echo "$line"
       fi

    done <<< "$lines"
share|improve this question

1 Answer 1

up vote 3 down vote accepted

There is a problem here if you have input that is not predictable (e.g. manual input). Unless you can tell the future you can't trivially (i.e. via the while read line construct) know what is next to last. Also, since the loop stops when input stops, you will have to store a certain line and act on it after its "turn in the loop". Not before then can you know if it was the last one. If the input is a fixed string or file, it is more of a theoretical consideration than a practical one.

A prototype for doing what you want:

unset lastline
while read line; do
    if ! [ -z "$lastline" ]; then
        echo "$lastline"
    fi
    lastline=$line
done <<< "$lines"
echo "This is the last one: $lastline"
  • unset lastline is just to "protect you" if you run the same script in e.g. a terminal multiple times, since $lastline then might not be empty to begin with. You could also clear it after the last echo if this might be an issue.
  • ! [ -z "$lastline" ] returns true if the $lastline variable is non-empty (technically if the length of the string is not zero). See man test if you are not used to these tests.

(Though my gut wants to ask you what you really are trying to do :-) .)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.