4

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"

1 Answer 1

3

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

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .