Run Golang script from shell script
Asked Answered
M

1

2

I'm trying to run my golang program whenever I log into OSX. I'm trying the following script with Automator:

#!/bin/sh
export GOPATH=/Volumes/DTSE9/worker
go run /Volumes/worker/worker.go

Whenever I run this with Automator, it tells me go: command not found

Mayworm answered 17/3, 2017 at 19:13 Comment(4)
So go isn't in the PATH. You either add it to the PATH, or us a full path.Rhododendron
@Rhododendron Do you mean add export GOROOT=/usr/local/go/bin/go above the first export? Just tried that and it doesn't work.Mayworm
No, don't set GOROOT (and that's not a valid value for GOROOT anyway). If /usr/local/go/bin isn't in your path, you need to add it to your PATH, or use /usr/local/go/bin/go runRhododendron
But why not just compile the program and run the executable? It will run faster and won't depend on the state of GOPATH.Rhododendron
H
3

Create a file like say file.go and it's content should look like:

///path-to/bin/go run $0 $@; exit $?

package main

func main() {
    println("Hello World!")
}

Then run chmod +x file.go and then you can execute it as ./file.go p1 p2.

Edit: This works on Ubuntu. I did not saw that OSX was in question.

This is another version of the first line which does not require the path to the go command (tested on zsh):

///$(which go) run $0 $@; exit $?
Hilmahilt answered 17/3, 2017 at 19:23 Comment(10)
lol, really taking the term "go script" literally, but it is a neat hack ;). It should run fine on macOS too.Rhododendron
Just tried that and got: go: unknown subcommand "./main.go" Run 'go help' for usage.Mayworm
You do not need to call go command anymore - just $ ./main.go. And I'm using it on Ubuntu; though I'm not familiar with OSX, but since it's a POSIX compatible OS (& as I understand, has bash), this should work on OSX too.Hilmahilt
@KavehShahbazian yeah, that's what I did. $ ./main.go and I got the above error message.Mayworm
Then it's something about OSX that I'm not aware of (but a guess is at the first line instead of /path-to/go run you just have /path-to/go).Hilmahilt
go build works, but how do I specify the full path when executing an executable? I'm trying .//Volumes/DTSE9/worker/mainMayworm
@KavehShahbazian Oh I was missing the run. Ok that worked, but how do I specify the absolute path to do the ./?Mayworm
This is the full path to your file. At the first line you should put full path to go binary itself.Hilmahilt
@KavehShahbazian No, I mean I'm trying to run a shell script from OSX Automator and the script is on my flash drive, so I'm trying to specify the absolute path for the shell script to execute the go executable.Mayworm
Let us continue this discussion in chat.Hilmahilt

© 2022 - 2024 — McMap. All rights reserved.