Bash – Write hexadecimal values to binary file with bash

bashbinary

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.

Best Answer

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.

Related Question