-
-
Save estraph/13310672b3195f977b580614f8b105d4 to your computer and use it in GitHub Desktop.
Run Go program as script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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:]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 toenv
and a comment in Golang, so this happens to work. It callsgo 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!