Hacker News new | past | comments | ask | show | jobs | submit login

Those strings also support things like \0 to get a null byte, and \uxxxx to get a Unicode character. This is useful for working with filenames and other things with spaces, quotes, and so on using find, xargs, etc. E.g.

  find ... -print0 | while read -d $'\0' f; do ...; done



"read" also supports the empty string to mean the null byte in this case:

    find ... -print0 | while read -d '' f; do ...; done
And since Bash 4.4, also "readarray"/"mapfile" can specify a delimiter, which is great to read files safely into an array:

    readarray -d '' -a arr < <(find ... -print0)


>Those strings also support things like \0 to get a null byte

WARNING: this is not true in bash!

You can have exactly one null byte in a bash string: the terminating null byte. Try this:

  echo $’foo\0bar’
It prints “foo”.

So practically you can’t have null bytes in bash strings, as it will be mistaken for the terminating null of the underlying C string.

In your example read -d ‘’ would work just the same; actually that’s the idiomatic way to iterate on zero-delimited input (or xargs -0). Why does the empty string work? Because -d takes the first char of the string as the delimiter, which for empty C strings is the terminating \0 - this is how bugs become features.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: