This all started when I wanted to make a program that could update itself. I figured I need the program to download a new version and run a function that copies the new program and replaces the original with the downloaded version.
I tried to make this problem as small as possible, how can I make a program that calls another program to remove itself, here is my attempt:
package main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"time"
)
func main() {
fmt.Println("program started")
remove := flag.Bool("rm", false, "removes test")
flag.Parse()
if *remove {
// Wait 5 seconds to let other program finish
time.Sleep(5 * time.Second)
// Try to remove program that started this program
fmt.Println("running rm")
err := os.Remove("./test")
if err != nil {
log.Fatalf("os.Remove() failed with %s
", err)
}
} else {
// Call the second program which will remove ./test which is currently running
fmt.Println("running remove program")
cmd := exec.Command("./remove", "-rm")
err := cmd.Start()
if err != nil {
log.Fatalf("cmd.Run() failed with %s
", err)
}
}
}
Here is how I call this via cli.
uberswe$ go build -o test
uberswe$ go build -o remove
uberswe$ ./test
program started
running remove program
uberswe$ ls -la
total 9048
drwxr-xr-x@ 6 uberswe staff 192 Apr 14 15:55 .
drwxr-xr-x@ 56 uberswe staff 1792 Apr 14 15:36 ..
drwxr-xr-x@ 6 uberswe staff 192 Apr 14 15:55 .idea
-rw-r--r--@ 1 uberswe staff 680 Apr 14 15:55 main.go
-rwxr-xr-x@ 1 uberswe staff 2311528 Apr 14 15:55 remove
-rwxr-xr-x@ 1 uberswe staff 2311528 Apr 14 15:55 test
So in summary: How can I make a program that can remove itself either on its own or via a second command/program?
Bonus if it is portable to different operating systems.