How to use `while read` (Bash) to read the last line in a file if there’s no newline at the end of the file?

后端 未结 7 864
臣服心动
臣服心动 2020-12-02 13:58

Let’s say I have the following Bash script:

while read SCRIPT_SOURCE_LINE; do
  echo \"$SCRIPT_SOURCE_LINE\"
done

I noticed that for files

7条回答
  •  伪装坚强ぢ
    2020-12-02 14:45

    I use the following construct:

    while IFS= read -r LINE || [[ -n "$LINE" ]]; do
        echo "$LINE"
    done
    

    It works with pretty much anything except null characters in the input:

    • Files that start or end with blank lines
    • Lines that start or end with whitespace
    • Files that don't have a terminating newline

提交回复
热议问题