Bash doesn't support null bytes in variables.
foo=$(cat file) makes
$foo contain the beginning of the file, up to the first null byte. The command substitution also strips all final newlines from the file. For example, if the file consists of the four bytes (
a, newline, newline, newline), then
foo contains just
a, same as if the file only contained that one byte.
If you want to preserve final newlines, arrange for the command to output an extra non-newline character, then strip it off.
foo=$(cat file; echo a)
So far this all worked in all Bourne/POSIX-style shells (ash, ksh, bash, …). Bash ≥4.0 has a faster way of reading a file into a variable: the
mapfile <file foo
There simply isn't a way to stuff a null byte into a bash variable. If you want this, you have several options:
- Use zsh.
- Use Perl.
- Store the data in a temporary file (which seems useless here, as the data is already in a file).
- Encode the input and decode it back, e.g. with