How can I write an specific number of zeros in a binary file automatically?

I write:

for i in {0..127};
    echo -e -n "\x00" >> file.bin

But looking the file with Bless outputs: 2D 65 20 2D 6E 20 5C 78 30 30 0A which corresponds to -e -n \x00.

  • 1
    Bash's builtin echo should process -e and -n, but just in case you're running that script with sh myscript.sh, take into account that sh might be a different shell. – ilkkachu Jul 10 '17 at 11:26

printf should be portable and supports octal character escapes:

while [ "$i" -le 127 ]; do
    printf '\000'
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.

  • @Wildcard Yes, it will. Which is precisely what the question requested. – Gilles 'SO- stop being evil' Jul 11 '17 at 23:58
  • Does this work for values other than nulls? – Zimba Jan 28 at 13:59

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' andcount` 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.

  • 2
    or just head -c123 /dev/zero >> file.bin for arbitrary values of 123. (no need to think explicitly about the block size) – ilkkachu Jul 10 '17 at 17:11
  • 1
    Mind that dd if=/dev/zero bs=128 count=1 >> file.bin' does append without cat or a new sub-shell (the pipe |`). – Isaac Jul 10 '17 at 21:41
  1. printf will re-use the same format for all arguments.
  2. The format %.0s will print no part of its argument.

Combining these leads to the rather nice

$ printf '\0%.0s' {1..128} >128nulls

for 128 nulls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.