What's the appropriate Go shebang line?

后端 未结 6 770
情书的邮戳
情书的邮戳 2021-02-01 01:55

I like using shebangs to run my Perl scripts directly:

#!/usr/bin/env perl

What\'s the shebang for Go programs?

6条回答
  •  春和景丽
    2021-02-01 02:00

    I prefer this:

    ///bin/true; exec /usr/bin/env go run "$0" "$@"
    

    This has several advantages compared to the answer by هومن جاویدپور:

    • Uses exec to replace the new shell process instead of launching a grandchild process. As a result, your Go program will be a direct child process. This is more efficient and it's also important for some advanced situations, such as debugging and monitoring.

    • Proper quoting of arguments. Spaces and special characters won't cause problems.

    • The leading /// is more standards compliant than just //. If you only use //, you run the risk of bumping into implementation-defined behaviour. Here's a quote from http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html:

    If a pathname begins with two successive / characters, the first component following the leading / characters may be interpreted in an implementation-defined manner, although more than two leading / characters shall be treated as a single / character.

    I have tested this answer with bash, dash, zsh, and ksh.

    Example:

    ///bin/true; exec /usr/bin/env go run "$0" "$@"
    package main
    import "fmt"
    func main() {
        fmt.Println("你好!")
    }
    

提交回复
热议问题