Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang - difference between os.stdout and multiwriter

Tags:

go

I have this code to run zsh and log its output to an output file.

package main

import (
    "io"
    "os"
    "os/exec"
)

func main() {

    cmd := exec.Command("zsh")
    f, _ := os.Create("log.txt")
    multiWriter := io.MultiWriter(os.Stdout, f)
    cmd.Stdout = multiWriter
    cmd.Stderr = os.Stderr
    cmd.Stdin = os.Stdin
    cmd.Run()
}    
func haltOnError(err error) {
    if err != nil {
        panic(err)
    }
}

when the program executes, typing ls will output

foo
bar

while if I let cmd.Stdout = os.Stdout, it displays correctly as

foo    bar

What leads to the differences between os.Stdout and multiwriter?

like image 554
boh Avatar asked Oct 31 '15 14:10

boh


1 Answers

Based on comments by @Time and @wldsvc

The cause of the problem is that isatty is used by ls to choose the default output format, in this case the use of io.MultiWriter and os.Stdout result in different decisions based on the result of isatty.

The proposed solution was to force the output format of ls by use of the parameters (man ls):

-C  list by columns
-x  list by lines instead of columns
-1  list one file per line

(documenting answer as show quiet high on unanswered list)

like image 70
miltonb Avatar answered Nov 06 '22 17:11

miltonb