Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);"
           echo "$line"

    done <<< "$lines"
share|improve this question
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"
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


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.