I am trying to figure out a way to execute a script (.sh) file from Golang. I have found a couple of easy ways to execute commands (e.g. os/exec), but what I am looking to do is to execute an entire sh file (the file sets variables etc.).
Using the standard os/exec method for this does not seem to be straightforward: both trying to input "./script.sh" and loading the content of the script into a string do not work as arguments for the exec function.
for example, this is an sh file that I want to execute from Go:
OIFS=$IFS; IFS=","; # fill in your details here dbname=testDB host=localhost:27017 collection=testCollection exportTo=../csv/ # get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys keys=`mongo "$host/$dbname" --eval "rs.slaveOk();var keys = []; for(var key in db.$collection.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`; # now use mongoexport with the set of keys to export the collection to csv mongoexport --host $host -d $dbname -c $collection --fields "$keys" --csv --out $exportTo$dbname.$collection.csv; IFS=$OIFS;
from the Go program:
out, err := exec.Command(mongoToCsvSH).Output() if err != nil { log.Fatal(err) } fmt.Printf("output is %s\n", out)
where mongoToCsvSH can be either the path to the sh or the actual content - both do not work.
Any ideas how to achieve this?
You can run Bash scripts in both Zsh and fish by adding the following shebang line to the first line of your Bash file.
Execute Shell Command Using the os/exec Package in Go Any OS or system command can be triggered using Go's os/exec package. It provides two functions that can be used to do this: Command, which creates the cmd object, and Output, which executes the command and returns the standard output.
For your shell script to be directly runnable you have to:
Start it with #!/bin/sh
(or #!/bin/bash
, etc).
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)
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With