bashnul

read nul delimited fields


Given this file

printf 'alpha\0bravo\0charlie' > delta.txt

I would like to read the fields into separate variables. The reason I am using a null separator is because the fields will contain file paths, which can contain any character except null. I tried these commands:

IFS= read mike november oscar < delta.txt
IFS=$'\0' read mike november oscar < delta.txt

However the fields are not being properly split

$ echo $mike
alphabravocharlie

Solution

  • As a workaround, I created this function

    function read-nul {
      while [ "$#" -gt 0 ]
      do
        read -d '' "$1"
        shift
      done
    }
    

    Example use

    read-nul mike november oscar < delta.txt