Ever wondered what it feels like to build a program that deletes itself after execution? Sounds crazy, right? Well, today, we are going to do just that, build a Self-Destructing CLI Tool in Go!
This is a fun experiment, but it also introduces some cool file handling and process management techniques in Go. Letโs get started!
How It Works
The idea is simple:
- The Go program executes normally.
- Before exiting, it deletes its own binary file.
- Once destroyed, the program is gone forever (unless you recompile it). ๐คฏ
Writing the Self-Destructing Go Code
1. Initialize a Go Project
First, create a new project directory and initialize a Go module:
mkdir self_destruct && cd self_destruct
go mod init self_destruct
Create a file named self_destruct.go
and add the following code:
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
fmt.Println("๐ Running self-destructing program...")
// Get the current executable path
exePath, err := os.Executable()
if err != nil {
fmt.Println("Failed to get executable path:", err)
return
}
// Print the file path before deletion
fmt.Println("Deleting:", exePath)
// Create a command to delete the file
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/C", "del", exePath)
} else {
cmd = exec.Command("sh", "-c", fmt.Sprintf("rm -f %s", exePath))
}
cmd.Start() // Start but don't wait to prevent blocking
}
Letโs break down what this code does:
-
os.Executable()
returns the absolute path of the currently running executable. -
fmt.Println("Deleting:", exePath)
: Prints the file path before deletion so the user can see whatโs happening. -
exec.Command("cmd", "/C", "del", exePath)
creates a command to delete the executable file. -
.Start()
runs the command asynchronously to ensure the program doesn't hang while deleting itself.
Running the Program
Compile the Program : go build .
Run the Program : ./self_destruct
The binary file deletes itself after execution! Try running it again youโll see itโs gone.
While this was a fun experiment, there are some real-world applications:
- Security & Privacy โ Temporary scripts that auto-delete after execution.
- Cleanup Mechanisms โ Self-cleaning build artifacts.
- One-Time Setup Scripts โ Ensure scripts donโt run twice.
This was a crazy but entertaining experiment with Goโs file handling and process execution.
Would you ever use this in real life? Or have any other wacky Go ideas? Let me know! ๐๐ฅ
Top comments (0)