Creates executable Go scripts with shebang-like behavior. Use when the user wants Go scripts, mentions Go scripting, or needs executable .go files. If working in a Go project, do NOT use unless explicitly requested.
Create executable Go scripts using a shell trick (not a true shebang). Scripts run directly like ./script.go with full argument support.
First line of any Go script (choose based on your shell):
// For dash (Debian/Ubuntu default):
//usr/bin/env go run "$0" "$@"; exit
// For bash/zsh (avoids gopls formatting complaints):
/**/usr/bin/env go run "$0" "$@"; exit;
Then chmod +x script.go and run ./script.go args.
Shell compatibility:
/**/ syntax works in bash/zsh but NOT in dash// syntax works in dash but gopls will complain about formatting/bin/sh: ls -l /bin/sh//usr/bin/env go to find go in PATH//usr/local/go/bin/go for absolute path./script.go as binary/bin/sh$0 = script path, $@ = all argumentsexit (or exit;) prevents shell from interpreting remaining Go code//path to /path or /**/path to /path//usr/bin/env go run "$0" "$@"; exit
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: ./script.go <name>")
os.Exit(1)
}
fmt.Printf("Hello, %s!\n", os.Args[1])
}
Good for:
Avoid for:
//usr/bin/env go run "$0" "$@"; exit
package main
import (
"flag"
"fmt"
)
func main() {
verbose := flag.Bool("v", false, "verbose output")
flag.Parse()
fmt.Printf("Verbose: %v, Args: %v\n", *verbose, flag.Args())
}
//usr/bin/env go run "$0" "$@"; exit
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println("Got:", scanner.Text())
}
}
//usr/bin/env go run "$0" "$@"; exit
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
fmt.Println(path)
}
return nil
})
}
env finds go in PATH, making scripts more portableexit; with /**/ syntax (but not with //)