Skip to content

Instantly share code, notes, and snippets.

@zored
Last active November 3, 2022 02:30
Show Gist options
  • Save zored/6ff3ffddb1deed3394e6d781a09ef1d8 to your computer and use it in GitHub Desktop.
Save zored/6ff3ffddb1deed3394e6d781a09ef1d8 to your computer and use it in GitHub Desktop.
Golang shebang for scripting
//usr/bin/env go run "$0" "$@"; exit "$?"
package main
import "fmt"
func main() {
fmt.Println("ok")
}

GoLang shebang for scripting

This is not really a shebang. Real one was rejected several times. But it still works:

  • When you run ./main.go then it's evaluated as shell-script (sh or bash). Pretty version of it looks like this:

    go run <current file> <arguments>
    
  • Go ignores first comment and executes as usually.

  • Exit code is handled correctly.

Details

  • //usr/bin/env go seeks for go binary and handles Go comment // correctly.
  • $0 "$@" passess current file and arguments to binary.
  • exit "$?" returns exit code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment