Home Execute Shell/Bash in Go
Reply: 0

Execute Shell/Bash in Go

user1931
1#
user1931 Published in April 25, 2018, 12:07 pm

I am trying to start a shell process in Go. This is my code:

func StartShell() (*Shell, error) {
    cmd := exec.Command("sh")

    stderr, err := cmd.StderrPipe()
    if err != nil {
        return nil, err
    }

    stdin, err := cmd.StdinPipe()
    if err != nil {
        return nil, err
    }

    stdout, err := cmd.StdoutPipe()
    if err != nil {
        return nil, err
    }

    if err := cmd.Start(); err != nil {
        return nil, err
    }

    sh := &Shell{
        cmd:       cmd,
        stderr:    stderr,
        stdin:     stdin,
        stdout:    stdout,
    }

    // this will read forever, but it is only for ilustrative purposes
    for {
        b := make([]byte, 2048)
        fmt.Println(stdout.Read(b))
    }

    return sh, nil
}

If I execute above function as it is, I will not get any output, however if I change sh to cmd and execute it on Windows, it prints some data at the beginning and waits forever (that is OK). Example output:

36 <nil>
129 <nil>

This led me to thinking that it may be Linux way. So I changed the command to ls and executed it on Linux. In short: it works as expected.

Next, I redirected stdout, stderr and stdin to the process ones. I've added following snippet just above cmd.Start():

// without those three below, `sh` would not print anything to stdout
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr

When executed now, I have fully operational sh process redirected to my terminal. It only works when all 3 streams are redirected.

Why does this happen? Ideally, I'd like to start shell process in a background and run commands from within that shell without printing it to terminal. (I am aware that this is not optimal solution.)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.354041 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO