Reading null delimited strings through a Bash loop Reading null delimited strings through a Bash loop bash bash

Reading null delimited strings through a Bash loop


The preferred way to do this is using process substitution

while IFS= read -r -d $'\0' file; do    # Arbitrary operations on "$file" heredone < <(find /some/path -type f -print0)

If you were hell-bent on parsing a bash variable in a similar manner, you can do so as long as the list is not NUL-terminated.

Here is an example of bash var holding a tab-delimited string

$ var=$(echo -ne "foo\tbar\tbaz\t"); $ while IFS= read -r -d $'\t' line ; do \    echo "#$line#"; \  done <<<"$var"#foo##bar##baz#


Use env -0 to output the assignments by the zero byte.

env -0 | while IFS='' read -d '' line ; do    var=${line%%=*}    value=${line#*=}    echo "Variable '$var' has the value '$value'"done


I tried working with the bash examples above, and finally gave up, and used Python, which worked the first time. For me it turned out the problem was simpler outside the shell. I know this is possibly off topic of a bash solution, but I'm posting it here anyway in case others want an alternative.

import shimport pathfiles = path.Path(".").files()for x in files:    sh.cp("--reflink=always", x, "UUU00::%s"%(x.basename(),))    sh.cp("--reflink=always", x, "UUU01::%s"%(x.basename(),))