I like using shebangs to run my Perl scripts directly:
#!/usr/bin/env perl
What's the shebang for Go programs?
Rules for the shebangThe shebang command must be the first line of the file and can contain any valid path for the interpreter, followed by an argument that the command will receive. The shebang line is read by the system before the execution of the program, but that line will not be automatically deleted.
What is bash shebang? The #! syntax is used in scripts to indicate an interpreter for execution under UNIX / Linux operating systems. The directive must be the first line in the Linux shell script and must start with shebang #! .
The shebang must be the first line because it is interpreted by the kernel, which looks at the two bytes at the start of an executable file. If these are #! the rest of the line is interpreted as the executable to run and with the script file available to that program.
The better shebang format is: #!/usr/bin/env python3.
//usr/bin/go run $0 $@ ; exit
example:
//usr/bin/go run $0 $@ ; exit package main import "fmt" func main() { fmt.Println("Hello World!") }
go treat //
as a single line comment and shell ignore extra /
Update: Go installation may be in a different location. The syntax below will take that into account, and works for Macs:
//$GOROOT/bin/go run $0 $@ ; exit
I prefer this:
///usr/bin/true; exec /usr/bin/env go run "$0" "$@"
This has several advantages compared to the answer by هومن جاویدپور:
The ///usr/bin/true
accomplishes the feat of simultaneously being valid Go and shell syntax. In Go it is a comment. In shell, it is no-op command.
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:
///usr/bin/true; exec /usr/bin/env go run "$0" "$@"
package main
import "fmt"
func main() {
fmt.Println("你好!")
}
There isn't one by default. There is a third-party tool called gorun that will allow you to do it, though. https://wiki.ubuntu.com/gorun
Unfortunately the compilers don't like the shebang line. You can't compile the same code you run with gorun.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With