26

As Go is becoming the language of the "system". I wonder if it's possible to run Go code as a script, without compiling it, is there any possibility to do that?

The motivation (as there were questions as for motivation), taken from How to use Scala as a scripting language

Problem You want to use Scala as a scripting language on Unix systems, replacing other scripts you’ve written in a Unix shell (Bourne Shell, Bash), Perl, PHP, Ruby, etc.

UPDATE: I wonder how much I can "abuse" go run to be able to have much Go code running as scripts though compiled (which I like that its compiled) but it looks like go run can give me the opportunity to replace scripting, that is have source files on servers and run them as source while getting compiled by the go run but I still manage sources and not executables.

UPDATE: in addition saw gorun

gorun - Script-like runner for Go source files.

Though there is a motivation and tools which tried to workaround not being able to run as script, I will not go for it, +I've been told it's not production ready and was advised not to use it in production because it's not production ready, it's out of it's purpose and would need dump the scripting convenience in favour of Go. (I don't have anything against compiling, static typing, I'm a big fan of it, but wanted something similar to scripting convenience).

5
  • 5
    nop, go is compiled language, and that s great.
    – user4466350
    Jan 9, 2017 at 7:30
  • 8
    Is go run main.go what you're looking for ? However, the code is still compiled under a temporary folder. Jan 9, 2017 at 7:30
  • update question with motivation
    – Jas
    Jan 9, 2017 at 8:21
  • @T.Claverie yes, this is what i was looking for, i'm cool with it that its compiled, i like static typing and compiling, was just wanted to have the ability to have the original scripts on target unix system to be run and not just compiled code, so people can look at the source, hopefully it would be possible to run .go files with imports and fully blown scripts. this would now enable me i think at least to replace other unix scripts such as Unix shell (Bourne Shell, Bash), Perl, PHP, Ruby with go scripts, what do you think?
    – Jas
    Jan 9, 2017 at 8:23
  • 1
    so people can look at the source, as a good developer, and not just a sysadmin with a bunch of scripts within some folder, i suspect you ll version your success with a vcs ? Won t you ? That will be a great way to share and let co workers checkout then study the source. Note that to go run means that the running system has a version of go installed, which may be heavy for some environments in comparison to the deployment of a compiled binary.
    – user4466350
    Jan 9, 2017 at 19:08

5 Answers 5

20

I am not an expert in go, but you can do something like this. I know this is not elegant, but may be something to start with :)

~$ cat vikas.go
//usr/bin/env go run "$0" "$@"; exit

package main

import "fmt"

func main() {
    fmt.Printf("Hello World\n")
}
~$

~$ ./vikas.go
Hello World
~$
3
  • 1
    To make this POSIX compliant the following would work. // 2>/dev/null||/usr/bin/go run $0 $@; exit $?. // is not necessarily equal to / in all spots of a path. POSIX allows the root of // to be interpreted in an implementation-defined manner (cygwin uses this for example). Three or more slashes would be considered equal to / again, though.
    – Grauwolf
    Nov 21, 2017 at 22:04
  • 1
    It's worth noting that this relies on a POSIX shell feature, rather than the kernel (which would require a #! she-bang line, and isn't compatible with "multi-word" commands like go run). As such, the script will only work when invoked by a shell (or shell script), not if invoked directly by a native app using exec*. Dec 17, 2019 at 15:08
  • ///usr/bin/true; exec /usr/bin/env go run "$0" "$@"; exit $? but i forgot why i came up with that
    – sjas
    Feb 14, 2022 at 15:22
9

As others noted, Go is a compiled language. Programs written in the Go language rely on the Go runtime which is added to the executable binary.

The Go runtime provides certain vital features such as garbage collection, goroutine scheduling, runtime reflection etc. Without them a Go app cannot work as guaranteed by the language spec.

A theoretical Go interpreter would have to simulate those features, which would essentially mean to include a Go runtime and a Go compiler. There is no such thing, and there is no need for that.
Also note that if the code is not yet compiled, that means the Go interpreter would have to contain all the standard library, because a Go "script" could legally refer to anything from the standard library (when a Go app is compiled, only things that it uses / refers to gets compiled into the executable binary).

To quickly test something, just use go run, which also compiles your app and builds an executable binary in a temporary folder, launches that temp file and cleans it when your app exits.

"Solutions" posted by others may "feel" like scripting, but they are nothing more than automating / hiding the process of compiling the Go source to an executable binary and then launching that binary. This is exactly what go run does (which also cleans up the temporary binary).

5
  • I wonder how much I can "abuse" go run to be able to have much go code running as scripts though compiled (which I like that its compiled) but it looks like go run can give me the opportunity to replace scripting my main interest is to manage sources on servers and not compiled code. (compilation is a huge benefit, static typing, ...) but still i want to deploy sources and run them as scripts.
    – Jas
    Jan 9, 2017 at 8:32
  • It's very easy (and very common) in a *nix environment. stackoverflow.com/questions/42865472/… Jan 2, 2018 at 20:17
  • @KavehShahbazian It "feels" like scripting, but in fact it's nothing more that automating / hiding the process of compiling the Go source into an executable binary and running it.
    – icza
    Jan 3, 2018 at 9:49
  • IMHO same thing applies when one uses Elixir or Clojure for scripting (they have JIT). Even strongly typed, compiled languages like Haskell and F# provide a REPL and in fact F# is used this way in many occasions. Though this is common only on *nix environments and not used by Windows folks. Jan 3, 2018 at 16:38
  • @Jas compile + run time of golang is orders of magnitude smaller than running all the interpreter languages from what i've seen
    – sjas
    Jun 19, 2018 at 19:46
8

Absolutely possible on linux, props to cf: https://blog.cloudflare.com/using-go-as-a-scripting-language-in-linux

In case you don't want to use the already mentioned 'shebang' which may have limitations:

//usr/bin/env go run "$0" "$@"; exit "$?"

Do this instead:

# check if binfmt_misc is already active 
# (should already be done through systemd)
mount | grep binfmt_misc

# if not already mounted
sudo mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc

# get gorun and place it so it will work
go get github.com/erning/gorun
sudo mv $GOPATH/bin/gorun /usr/local/bin

# make .go scripts being run with `gorun` wrapper script
echo ':golang:E::go::/usr/local/bin/gorun:OC' | sudo tee /proc/sys/fs/binfmt_misc/register

This is just for one-off testing. To make this persistant, I have this as the second last line in my /etc/rc.local's:

echo ':golang:E::go::/usr/local/bin/gorun:OC' | tee /proc/sys/fs/binfmt_misc/register 1>/dev/null

If you experience something like 'caching' issues during developing scripts, have a look at /tmp/gorun-$(hostname)-USERID.

I love bash, but as soon as you need a proper datastructures (bash arrays and associative arrays don't count due to unusability) you need another language. Golang is faster to write for me than is python, and any golang setup as depicted above will do for me. No battling python 2 vs 3, its libs and pip horrors, have a distributable binary at will, and just instantly be able to change the source for small one-off scripts is why this approach has definitely its upsides.

1
  • 1
    this is the right answer, and you'll note it's newer than the others, I suppose that's why it's not at the top just yet... Mar 24, 2019 at 8:06
3

see Neugram, Go scripting . From it's documentation:

#!/usr/bin/ng

// Start a web server to serve files.
import "net/http"
pwd := $$ echo $PWD $$
h := http.FileServer(http.Dir(pwd))
http.ListenAndServe(":8080", h)
2
  • neugram looks pretty dead, according to the github commits.
    – sjas
    Dec 19, 2019 at 17:47
  • 1
    This project died in March 2018. Dec 25, 2020 at 12:21
-6

No this is neither possible nor desirable.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.