Executing Bash Scripts Seamlessly from Go
Executing a bash script from Golang can pose challenges using the standard os/exec method. To execute an entire sh file effectively, follow these steps:
For Direct Execution:
Using /bin/sh with Script Path:
cmd := exec.Command("/bin/sh", mongoToCsvSH)
Example Script (assuming path and executable permissions set):
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;
Go Code:
var mongoToCsvSH string func executeMongoToCsv() { out, err := exec.Command(mongoToCsvSH).Output() if err != nil { log.Fatal(err) } fmt.Printf("output is %s\n", out) }
Conclusion:
Following these steps, you can execute a bash script from Golang effectively, either directly or via /bin/sh.
The above is the detailed content of How Can I Seamlessly Execute Bash Scripts from Go?. For more information, please follow other related articles on the PHP Chinese website!