Bash read ignores leading spaces

前端 未结 2 2076
既然无缘
既然无缘 2020-12-01 12:09

I have file a.txt with following content

    aaa
    bbb

When I execute following script:

while read line
do
          


        
2条回答
  •  无人及你
    2020-12-01 12:35

    There are several problems here:

    • Unless IFS is cleared, read strips leading and trailing whitespace.
    • echo $line string-splits and glob-expands the contents of $line, breaking it up into individual words, and passing those words as individual arguments to the echo command. Thus, even with IFS cleared at read time, echo $line would still discard leading and trailing whitespace, and change runs of whitespace between words into a single space character each. Additionally, a line containing only the character * would be expanded to contain a list of filenames.
    • echo "$line" is a significant improvement, but still won't correctly handle values such as -n, which it treats as an echo argument itself. printf '%s\n' "$line" would fix this fully.
    • read without -r treats backslashes as continuation characters rather than literal content, such that they won't be included in the values produced unless doubled-up to escape themselves.

    Thus:

    while IFS= read -r line; do
      printf '%s\n' "$line"
    done
    

提交回复
热议问题