while IFS= read -r -d $'\0' file … explanation

后端 未结 4 470
逝去的感伤
逝去的感伤 2021-01-01 04:06

I do not understand this line of shell script. Doesn\'t the while statement need a \'test\' or [ ] or [[ ]] expression that will set $? to 1 or 0? How does

w         


        
4条回答
  •  执念已碎
    2021-01-01 04:38

    In Bash, varname=value command runs command with the environment variable varname set to value (and all other environment variables inherited normally). So IFS= read -r -d $'\0' runs the command read -r -d $'\0' with the environment variable IFS set to the empty string (meaning no field separators).

    Since read returns success (i.e., sets $? to 0) whenever it successfully reads input and doesn't encounter end-of-file, the overall effect is to loop over a set of NUL-separated records (saved in the variable REPLY).

    Doesn't the while statement need a 'test' or [ ] or [[ ]] expression that will set $? to 1 or 0?

    test and [ ... ] and [[ ... ]] aren't actually expressions, but commands. In Bash, every command returns either success (setting $? to 0) or failure (setting $? to a non-zero value, often 1).

    (By the way, as nosid notes in a comment above, -d $'\0' is equivalent to -d ''. Bash variables are internally represented as C-style/NUL-terminated strings, so you can't really include a NUL in a string; e.g., echo $'a\0b' just prints a.)

提交回复
热议问题