1

I have a script called test.sh which processes the standard input line by line like this:

#!/usr/bin/env bash

echo "start"
while IFS= read -r line; do
    echo "processing[$line]"
done < /dev/stdin
echo "done"

The problem with this is, it doesn't process the characters between the last newline and the eof.

printf $'line 1\nline 2\nlast chars' | test.sh

will output

start
processing[line 1]
processing[line 2]
done

The reason I read line by line is that I need to inspect the first line and in some cases I want to remove it from the output stream.

How can I process these last characters? I've looked into read -n but then I would need to supply how many characters to expect at a maximum and I rather don't build in limits.

Also: I wouldn't know where to put this statement in the while-loop. I'm on the macOS platform.

doekman
  • 18,750
  • 20
  • 65
  • 86
  • Only `\n` are used. – doekman May 30 '18 at 11:01
  • 1
    To summarize the problem your problem, `read` fails if it doesn't see a newline termination, so for the last line it will return a non-zero exit code, simply add a check as `read -r line || [[ -n "$line" ]]` – Inian May 30 '18 at 11:10
  • Ah, `read` **does** read the last chars. I didn't realize this. And a nice solution for the condition; I'd never have thought of that. Thanks! – doekman May 30 '18 at 11:39
  • One caveat though: you can't distinguish between the two cases, but then I realized the last chars are also available within `$line` after the `while` loop, so I can use `printf` to write the last line without a new line. – doekman May 30 '18 at 11:53

0 Answers0