1

I am able to get the following command to open a new terminal and execute the command when I directly input it inside a terminal, but I can not get it to work when I use the exec.Commmand function in go.

osascript -e 'tell application "Terminal" to do script "echo hello"'

I think the issue lies within the double and single quotes, but I am not exactly sure what is causing the error.

c := exec.Command("osascript", "-e", "'tell", "application", `"Terminal"`, "to", "do", "script", `"echo`, `hello"'`)
if err := c.Run(); err != nil {
     fmt.Println("Error: ", err)
}

As of now the code is returning Error: exit status 1, but I would like the code to open a terminal window and execute the command.

3
  • 2
    tell application "Terminal" to do script "echo hello" is a single argument (the second) to osascript. play.golang.org/p/Rp_r8Jj7yve Commented Jul 17, 2019 at 15:16
  • I don't know about go but have you tried fixing the part of your code `"echo`, `hello"'` Commented Jul 17, 2019 at 15:17
  • Thanks @Peter you are right it is one argument. Commented Jul 17, 2019 at 15:21

1 Answer 1

2

After playing some time found this:

cmd := exec.Command("osascript", "-s", "h", "-e",`tell application "Terminal" to do script "echo test"`)

Apparently you should give the automator script in 1 argument and also use ticks (`) as the string literals for go.

"-s", "h" is for automator program to tell you human readable errors.

My complete test code is as follows:

package main

import (
    "fmt"
    "os/exec"
    "io/ioutil"
    "log"
    "os"
 )
// this is a comment

func main() {
    // osascript -e 'tell application "Terminal" to do script "echo hello"'
    cmd := exec.Command(`osascript`, "-s", "h", "-e",`tell application "Terminal" to do script "echo test"`)
    // cmd := exec.Command("sh", "-c", "echo stdout; echo 1>&2 stderr")
    stderr, err := cmd.StderrPipe()
    log.SetOutput(os.Stderr)

    if err != nil {
        log.Fatal(err)
    }

    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }

    slurp, _ := ioutil.ReadAll(stderr)
    fmt.Printf("%s\n", slurp)

    if err := cmd.Wait(); err != nil {
        log.Fatal(err)
    }
}

PS: osascript is the command line interface for Automator app in macOS.

Sign up to request clarification or add additional context in comments.

3 Comments

`osascript` == "osascript", there is no difference at all in the actual string. You should normally only use backticks when necessary, and prefer double-quotes when possible.
difference is in the last part. It is tricky to give a script as an argument. So double quotes works in ticks.
yes, that's when you would use `` to avoid escaping many quotes.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.