How to Write a Go Script That Runs Like a Shell Script

Cli
Write a Go program with a main function and run it using go run or compile it to a binary for shell-script-like execution.

Write a Go program with a main function, compile it to a binary, and execute it directly or via go run to achieve shell-script-like behavior. Unlike shell scripts, Go requires compilation, but the resulting binary runs natively without an interpreter.

package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: script <arg>")
		os.Exit(1)
	}
	fmt.Println("Running with:", os.Args[1])
}

Run it with go run script.go hello or compile and run with go build -o script script.go && ./script hello.