Home Execute Shell/Bash in Go
Reply: 0

Execute Shell/Bash in Go

user1975 Published in July 16, 2018, 3:07 am

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 illustrative purposes
    for {
        b := make([]byte, 2048)

    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 three 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.307103 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO