简体   繁体   中英

Golang - Execute command

Prompt as in golang to execute such command:

/bin/bash script.sh < text.txt

I execute a script with parameters so:

package main

import (
    "fmt"
    "os/exec"
    "log"
    "os"
)

func main() {
    argstr := []string{"script.sh", "arg1", "arg2"}
    out, err := exec.Command("/bin/bash", argstr...).Output()
    if err != nil {
        log.Fatal(err)
        os.Exit(1)
    }
    fmt.Println(string(out))
}

And here is how to transfer an output from the text file?

The command you should execute is:

/bin/bash -c 'script.sh < text.txt'

So

argstr := []string{"-c", "script.sh < text.txt"}

Bash will interpret input redirection and will do the job.

Pro Tip: Don't forget to timeout

ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
argstr := []string{"/bin/bash", "-c", "script.sh < text.txt"}
cmd := exec.CommandContext(ctx, argstr...)
cmd.Stderr = &errorBuffer
cmd.Stdout = &outputBuffer
err := cmd.Run()
if err != nil {
    return fmt.Errorf("something bad happened: %v", err)
}

I always suggest to play safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM