Bash – Read a line-oriented file which may not end with a newline

bashnewlinesshelltext processing

I have a file named /tmp/urlFile where each line represents a url. I am trying to read from the file as follows:

cat "/tmp/urlFile" | while read url
do
    echo $url
done

If the last line doesn't end with a newline character, that line won't be read. I was wondering why?

Is it possible to read all the lines, regardless if they are ended with a new line or not?

Best Answer

You'd do:

while IFS= read -r url || [ -n "$url" ]; do
  printf '%s\n' "$url"
done < url.list

(effectively, that loop adds back the missing newline on the last (non-)line).

See also:

Related Question