bash bite: variable eats null
bash variable cannot store null
(aka \0
) character;
as soon as you store a string containing null
into a bash variable, null
is
gone;
so it is dangerous to read binary data into a bash variable;
example 0
read a string with null
into a variable;
$ echo -ne "a\x00b\x00c\x00" > a.in
$ hexdump -C a.in
00000000 61 00 62 00 63 00 |a.b.c.|
00000006
$ IFS= read a < a.in
$ echo -n "$a" | hexdump -C
00000000 61 62 63 |abc|
00000003
example 1
use command substitution with a variable:
$ echo -ne "a\x00b\x00c\x00" > a.in
$ hexdump -C a.in
00000000 61 00 62 00 63 00 |a.b.c.|
00000006
$ a="$(<a.in)"
-bash: warning: command substitution: ignored null byte in input
$ echo -n "$a" | hexdump -C
00000000 61 62 63 |abc|
00000003
example 2
use command substitution in a command line:
$ echo -ne "a\x00b\x00c\x00" > a.in
$ hexdump -C a.in
00000000 61 00 62 00 63 00 |a.b.c.|
00000006
$ echo -n "$(<a.in)" | hexdump -C
-bash: warning: command substitution: ignored null byte in input
00000000 61 62 63 |abc|
00000003