Home > Backend Development > Golang > How Can I Seamlessly Execute Bash Scripts from Go?

How Can I Seamlessly Execute Bash Scripts from Go?

Susan Sarandon
Release: 2024-12-16 14:32:12
Original
991 people have browsed it

How Can I Seamlessly Execute Bash Scripts from Go?

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:

  1. Prefix the script with #!/bin/sh (or #!/bin/bash).
  2. Make the script executable using chmod x .

Using /bin/sh with Script Path:

  • If you prefer not to make the script executable, invoke /bin/sh and provide the script path as an argument:
cmd := exec.Command("/bin/sh", mongoToCsvSH)
Copy after login

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;
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template