-3

I have a file to which I've written the go run header, but the file isn't executing.

This site shows an example that doesn't work for me. https://coderwall.com/p/_kdjzq/go-run-run-go-as-a-script-language

./scripts/test.go

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

package scripts

import (
    "fmt"
)

func main() {
    fmt.Println("hello")
}

I am trying to invoke it like this:

chmod +x ./scripts/test.go
./scripts/test.go

Failed to execute process './scripts/test.go'. Reason:
exec: Exec format error
The file './scripts/test.go' is marked as an executable but could not be run by the operating system.
BAR
  • 15,909
  • 27
  • 97
  • 185
  • How exactly are you expecting this to work? You can’t just take any language source code and run it like a script. You can pass something like this to a shell, but why? See also https://stackoverflow.com/questions/7707178/whats-the-appropriate-go-shebang-line – JimB May 25 '21 at 00:51
  • 1
    Go must be compiled before you can execute it. – prieber May 25 '21 at 01:12
  • Does this answer your question? [What's the appropriate Go shebang line?](https://stackoverflow.com/questions/7707178/whats-the-appropriate-go-shebang-line) – bereal May 28 '21 at 06:59

2 Answers2

3

A Go file cannot be an executable file, by definition [1].

Please, do not try to treat it as such. Just run go install [2], then you can run the resultant program from any path.

  1. Should I use a Shebang with Bash scripts?
  2. https://golang.org/cmd/go/#hdr-Compile_and_install_packages_and_dependencies
Zombo
  • 1
  • 62
  • 391
  • 407
0

Go is a compiled language, not an interpreted one. To run a go file properly, first compile it via go build <go file>. If you want to run go as an interpreted language, you can use a go interpreter called yaegi.

Arsen6331
  • 1
  • 1
  • 4