Skip to content

Instantly share code, notes, and snippets.

@msoap
Last active October 8, 2022 17:23
Show Gist options
  • Save msoap/a9ee054f80a58b16867c to your computer and use it in GitHub Desktop.
Save msoap/a9ee054f80a58b16867c 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:])
}
@msoap
Copy link
Author

msoap commented Mar 16, 2018

@artheus
Copy link

artheus commented Aug 22, 2018

I would add one thing. I haven't tester that it work properly. But adding $? as argument to exit, should allow exit code to be set properly.

@msoap
Copy link
Author

msoap commented Sep 3, 2018

Unfortunately, this does not work properly. The exit code is always 1 or 0.

@jsolbrig
Copy link

@msoap There is no way to get the correct error code from go run, unfortunately. See here: https://stackoverflow.com/questions/55731760/go-os-exit2-show-a-bash-value-of-1

@pdk
Copy link

pdk commented Oct 4, 2020

I tested (very briefly) on macos with os.Exit(1) and os.Exit(7). What I see in this env is that the exit code is propagated, and can be captured with $? in the calling shell.

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