[Bash] How do I work with binary data and file I/O in Bash?

Here are some ways to work with binary data and file I/O in Bash:

  • Using the od command: The od command can be used to display the contents of a file in octal, decimal, hexadecimal, or ASCII format. This can be useful for debugging binary files or for extracting specific pieces of data from a file.
  • Using the read command: The read command can be used to read data from a file. By setting the -r option, the read command will read the data as binary. This can be useful for reading data that is not in text format, such as images or executable files.
  • Using the write command: The write command can be used to write data to a file. By setting the -b option, the write command will write the data as binary. This can be useful for writing data that is not in text format, such as images or executable files.
  • Using the dd command: The dd command is a versatile command that can be used to copy, convert, and format data. It can be used to read and write binary data, as well as to perform other operations on binary files.

Here is an example of how to use the read command to read binary data from a file:

 1#!/bin/bash
 2
 3# Open the file in binary mode
 4file=binary.bin
 5
 6# Read 10 bytes from the file
 7data=$(read -r -b 10 $file)
 8
 9# Print the data
10echo $data

This code will open the file binary.bin in binary mode and read 10 bytes from the file. The data will then be printed to the console.

Here is an example of how to use the write command to write binary data to a file:

 1#!/bin/bash
 2
 3# Create a new file
 4file=binary.bin
 5
 6# Write the data to the file
 7write -b 10 "Hello, world!" $file
 8
 9# Check the contents of the file
10cat $file

This code will create a new file called binary.bin and write the string "Hello, world!" to the file in binary format. The contents of the file can then be checked using the cat command.