Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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.

like image 365
clearcom0 Avatar asked Aug 13 '13 19:08

clearcom0


1 Answers

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.)

like image 192
ruakh Avatar answered Nov 15 '22 05:11

ruakh