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
while IFS= read -r -d $'\0'; do ...; done
do that? Any help understanding the syntax here is greatly appreciated.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With