package main import ( "fmt" "os" "os/exec" ) // setTitle prints the escape sequence to change the terminal title. func setTitle(title string) { fmt.Printf("\033]2;%s\007", title) } // resetTitle prints the escape sequence to clear the title. // Most terminals will revert to their default profile title. func resetTitle() { fmt.Printf("\033]2;\007") } func setTerminalTitle(title string, command string, args []string) { // 2. Defer the title reset. This is the crucial part. // `defer` ensures that resetTitle() is called right before the main function exits, // no matter what happens—success, error, or panic. defer resetTitle() setTitle(title) cmd := exec.Command(command, args...) // 5. Connect the command's I/O to our program's I/O. // This makes the command fully interactive and ensures you see its output. cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr // 6. Run the command. err := cmd.Run() // 7. If the command failed, exit with its status code to be a good citizen. if err != nil { // Try to get the original exit code. if exitError, ok := err.(*exec.ExitError); ok { os.Exit(exitError.ExitCode()) } else { // A different error occurred (e.g., command not found). fmt.Fprintf(os.Stderr, "Error running command: %v\n", err) os.Exit(1) } } }