how to backup raspberry pi sd card

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("sudo", "dd", "if=/dev/mmcblk0", "of=/path/to/backup.img", "bs=4M")
    output, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Backup completed successfully:", string(output))
}

Explanation: 1. Import the required packages fmt for formatted I/O and os/exec for running external commands in Go.

  1. Define the main() function as the entry point of the program.

  2. Use exec.Command to create a command to be executed. In this case, the command is sudo dd if=/dev/mmcblk0 of=/path/to/backup.img bs=4M.

  3. sudo: Runs the subsequent command with superuser privileges.
  4. dd: Command used for low-level copying.
  5. if=/dev/mmcblk0: Specifies the input file, which is the Raspberry Pi SD card (/dev/mmcblk0 is often the SD card device on Raspberry Pi).
  6. of=/path/to/backup.img: Specifies the output file where the backup will be saved. Change /path/to/backup.img to the desired location and filename.
  7. bs=4M: Sets the block size to 4 megabytes for faster copying.

  8. Execute the command using cmd.CombinedOutput() which runs the command and returns the combined standard output and standard error.

  9. Check if there's any error while executing the command. If an error occurs, print the error message.

  10. If the backup process completes successfully, print a success message along with the output generated by the command.