Shell: How to read the bytes of a binary file and print as hexadecimal?

Use hexdump(1)

$ hexdump -x /usr/bin/hexdump 
0000000    feca    beba    0000    0300    0001    0700    0080    0300
0000010    0000    0010    0000    5080    0000    0c00    0000    0700
0000020    0000    0300    0000    00a0    0000    b06f    0000    0c00
0000030    0000    1200    0000    0a00    0100    0010    0000    107c
0000040    0000    0c00    0000    0000    0000    0000    0000    0000
0000050    0000    0000    0000    0000    0000    0000    0000    0000

...


Another option is od:

od -t x1 FILE

or

od -x FILE

od has many options for finetuning.


While we're on od and hexdump, two more similar tools:

  • hd (from bsdmainutils)
  • xxd (part of Vim)

Sample output:

$ hd /usr/bin/od | head
00000000  7f 45 4c 46 01 01 01 00  00 00 00 00 00 00 00 00  |.ELF............|
00000010  02 00 03 00 01 00 00 00  20 8e 04 08 34 00 00 00  |........ ...4...|
00000020  a4 a2 00 00 00 00 00 00  34 00 20 00 08 00 28 00  |........4. ...(.|
00000030  1b 00 1a 00 06 00 00 00  34 00 00 00 34 80 04 08  |........4...4...|
00000040  34 80 04 08 00 01 00 00  00 01 00 00 05 00 00 00  |4...............|
00000050  04 00 00 00 03 00 00 00  34 01 00 00 34 81 04 08  |........4...4...|
00000060  34 81 04 08 13 00 00 00  13 00 00 00 04 00 00 00  |4...............|
00000070  01 00 00 00 01 00 00 00  00 00 00 00 00 80 04 08  |................|
00000080  00 80 04 08 c4 9d 00 00  c4 9d 00 00 05 00 00 00  |................|
00000090  00 10 00 00 01 00 00 00  00 a0 00 00 00 20 05 08  |............. ..|

$ xxd /usr/bin/od | head
0000000: 7f45 4c46 0101 0100 0000 0000 0000 0000  .ELF............
0000010: 0200 0300 0100 0000 208e 0408 3400 0000  ........ ...4...
0000020: a4a2 0000 0000 0000 3400 2000 0800 2800  ........4. ...(.
0000030: 1b00 1a00 0600 0000 3400 0000 3480 0408  ........4...4...
0000040: 3480 0408 0001 0000 0001 0000 0500 0000  4...............
0000050: 0400 0000 0300 0000 3401 0000 3481 0408  ........4...4...
0000060: 3481 0408 1300 0000 1300 0000 0400 0000  4...............
0000070: 0100 0000 0100 0000 0000 0000 0080 0408  ................
0000080: 0080 0408 c49d 0000 c49d 0000 0500 0000  ................
0000090: 0010 0000 0100 0000 00a0 0000 0020 0508  ............. ..

Or, if you want to read the bytes one at a time and print them in your own format, try something like:

while read -n 1 byte; do
    ord=$(printf "%b" "${byte:-\000}" |
          od -t x1 |
          { read offset hex; echo $hex; })
    echo "$ord"
done </usr/bin/od

Sample output:

7f
45
4c
46
01
01
01
00
00
00