Write hexadecimal values to binary file with bash
If it's zeros to a file, then the obvious one is:
dd if=/dev/zero of=file.bin bs=1 count=128
Note that this is pretty inefficient as it goes, as it does single byte writes. You could just as easily use:
dd if=/dev/zero of=file.bin bs=128 count=1
Here, bs' is the 'block size' and
count` is how many blocks. Better to write one block than lots of little ones!
Note that the above commands do not append to file.bin
, they overwrite it. One way round that is:
dd if=/dev/zero bs=128 count=1 >> file.bin
Explanation: in the absence of of=
, dd
writes to standard output, which is then appended to the output file.
printf
should be portable and supports octal character escapes:
i=0
while [ "$i" -le 127 ]; do
printf '\000'
i=$((i+1))
done >> file.bin
(printf
isn't required to support hex escapes like \x00
, but a number of shells support that.)
See Why is printf better than echo? for the troubles with echo
.