0

I am trying to read all inputs using while loop and print them again, but for some reason doesn't read the final input.. What's going on?

#!/usr/bin/env bash

while read -r num; do
    echo $num
done
Input (stdin):
4
1
2
9
8
Output (stdout):
4
1
2
9
# Last input is missing :(
Expected Output:
4
1
2
9
8
getimad
  • 1
  • 2
  • That is weird, using the exact same code, whenever I input something it's printed out. – Loïc Dec 09 '22 at 08:50
  • 2
    Probably your file doesn't end with a newline. Try `while read -r num || [[ $num ]];` – M. Nejat Aydin Dec 09 '22 at 08:53
  • @Loïc Create a text file (.txt) in the same directory and write all numbers on it. then use this command `./main.sh < file.txt ` in your terminal. – getimad Dec 09 '22 at 08:57
  • Your file is probably missing the final line break. To verify this post the output of: `hexdump -C file.txt` – Cyrus Dec 09 '22 at 09:30
  • 1
    Do the answers to ["Shell script read missing last line"](https://stackoverflow.com/questions/12916352/shell-script-read-missing-last-line) and ["Respect last line if it's not terminated with a new line char (\n) when using read"](https://stackoverflow.com/questions/14544636/respect-last-line-if-its-not-terminated-with-a-new-line-char-n-when-using-re) solve your problem? – Gordon Davisson Dec 09 '22 at 09:46

1 Answers1

1

You may forget to add a new line at the end of input.

4
1
2
9
8 # A new line expected, after the character "8".

Or we say, 4\n1\n2\n9\n8\n.

Otherwise, the last line won't be "enter"ed into the script / program.

Geno Chen
  • 4,916
  • 6
  • 21
  • 39
  • Hmmm, So is there a way to read all lines from the file as it, without adding an empty line at the end. – getimad Dec 09 '22 at 09:18
  • @getimad No. It is similar when you enter the `8` then immediately `Ctrl` + `C`: the `8` won't be read into the program / script. – Geno Chen Dec 09 '22 at 09:28
  • 3
    This is incorrect; you don't need a blank line at the end, just a terminating newline (aka linefeed character) at the end of each line, including the last one. – Gordon Davisson Dec 09 '22 at 09:45
  • @GordonDavisson Yes, my failure on using words. It should be "a new line", not "an empty line". Fixed. – Geno Chen Dec 09 '22 at 09:47
  • 1
    @GenoChen Your example is still at least misleading. The line starting with "#" should not be there (and I don't mean it should be blank, I mean that line should not be there at all). The newline character is an implicit part of the "8" line. – Gordon Davisson Dec 12 '22 at 09:54
  • @GordonDavisson I edited to try to clarify it. I just think of the `git diff`'s "No new line at end of file" notation, and wrote like that. Thank you for your clarification. – Geno Chen Dec 13 '22 at 02:04