5

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

I write:

#!/bin/bash for i in {0..127}; do echo -e -n "\x00" >> file.bin done 

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
  • 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
    CommentedJul 10, 2017 at 11:26

3 Answers 3

5

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.

2
  • @Wildcard Yes, it will. Which is precisely what the question requested.CommentedJul 11, 2017 at 23:58
  • Does this work for values other than nulls?
    – Zimba
    CommentedJan 28, 2021 at 13:59
5

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
  • 2
    or just head -c123 /dev/zero >> file.bin for arbitrary values of 123. (no need to think explicitly about the block size)
    – ilkkachu
    CommentedJul 10, 2017 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 |`).
    – user232326
    CommentedJul 10, 2017 at 21:41
1
  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.

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.