Skip to content

Instantly share code, notes, and snippets.

@estraph
Forked from msoap/script.go
Created May 3, 2017 22:38
Show Gist options
  • Save estraph/13310672b3195f977b580614f8b105d4 to your computer and use it in GitHub Desktop.
Save estraph/13310672b3195f977b580614f8b105d4 to your computer and use it in GitHub Desktop.
Run Go program as script
//usr/bin/env go run $0 "$@"; exit
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello world!")
cwd, _ := os.Getwd()
fmt.Println("cwd:", cwd)
fmt.Println("args:", os.Args[1:])
}
@estraph
Copy link
Author

estraph commented May 3, 2017

Why this works: http://www.faqs.org/faqs/unix-faq/faq/part3/section-16.html

tl;dr: magic number not detected (e.g. shebang #!), so falls back to treating like a script and running it with /bin/sh. The first line coincidentally is a call to env and a comment in Golang, so this happens to work. It calls go run with the same file path, and exits at the end of that first invocation. Go ignores the exit because it's in the comment, and runs the Go code instead.

Nifty!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment