4

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It works! Also I found one more method: func main() { cmd := exec.Command("/bin/bash", "script.sh") cmd.Stdin = strings.NewReader("text of the test.txt file") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) os.Exit(1) } fmt.Println(out.String()) }
@Konstantin You can add the other method as a new answer. I would just use os.Open to read the file.
Hello! Yes, it is already possible! Thank you for the help! Whether interestingly, perhaps to make similar not only through execution of bash-commands (a package of "os/exec"), and through implementation of the client of ssh (for example, means of a package of "crypto/ssh")?
0

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.

2 Comments

Is it for some other question?
Yeah, thinking better. The title and the question were somewhat confusing. :\ Looks like the problem it's pretty much about how to handle parameters with exec.Command() and bash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.