Executing a Bash Script from Golang

This worked for me

func Native() string {
    cmd, err := exec.Command("/bin/sh", "/path/to/file.sh").Output()
    if err != nil {
    fmt.Printf("error %s", err)
    }
    output := string(cmd)
    return output
}

For your shell script to be directly runnable you have to:

  1. Start it with #!/bin/sh (or #!/bin/bash, etc).

  2. You have to make it executable, aka chmod +x script.

If you don't want to do that, then you will have to execute /bin/sh with the path to the script.

cmd := exec.Command("/bin/sh", mongoToCsvSH)

You need to execute /bin/sh and pass the script itself as an argument.

Tags:

Bash

Go