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.
Define the
main()
function as the entry point of the program.Use
exec.Command
to create a command to be executed. In this case, the command issudo dd if=/dev/mmcblk0 of=/path/to/backup.img bs=4M
.sudo
: Runs the subsequent command with superuser privileges.dd
: Command used for low-level copying.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).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.bs=4M
: Sets the block size to 4 megabytes for faster copying.Execute the command using
cmd.CombinedOutput()
which runs the command and returns the combined standard output and standard error.Check if there's any error while executing the command. If an error occurs, print the error message.
If the backup process completes successfully, print a success message along with the output generated by the command.