Shell script read missing last line

前端 未结 7 1160
逝去的感伤
逝去的感伤 2020-11-22 12:57

I have an ... odd issue with a bash shell script that I was hoping to get some insight on.

My team is working on a script that iterates through lines in a file and

相关标签:
7条回答
  • 2020-11-22 13:52

    Adding some additional info:

    1. There's no need to use cat with while loop. while ...;do something;done<file is enough.
    2. Don't read lines with for.

    When using while loop to read lines:

    1. Set the IFS properly (you may lose indentation otherwise).
    2. You should almost always use the -r option with read.

    with meeting the above requirements a proper while loop will look like this:

    while IFS= read -r line; do
      ...
    done <file
    

    And to make it work with files without a newline at end (reposting my solution from here):

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

    Or using grep with while loop:

    while IFS= read -r line; do
      echo "$line"
    done < <(grep "" file)
    
    0 讨论(0)
提交回复
热议问题