This section will present a technique for sending data to UNIX standard error, which is the UNIX way of differentiating between actual values and error output.
The Go code for illustrating the use of standard error in Go is included in stdERR.go and will be presented in two parts. As writing to standard error requires the use of the file descriptor related to standard error, the Go code of stdERR.go will be based on the Go code of stdOUT.go.
The first part of the program is as follows:
package main import ( "io" "os" ) func main() { myString := "" arguments := os.Args if len(arguments) == 1 { myString = "Please give me one argument!" } else { myString = arguments[1] }
So far, stdERR.go is almost identical to stdOUT.go.
The second portion of stdERR.go is the following:
io.WriteString(os.Stdout, "This is Standard output\n") io.WriteString(os.Stderr, myString) io.WriteString(os.Stderr, "\n") }
You call io.WriteString() two times to write to standard error (os.Stderr) and one more time to write to standard output (os.Stdout).
Executing stdERR.go will create the following output:
$ go run stdERR.go This is Standard output Please give me one argument!
The preceding output cannot help you to differentiate between data written to standard output and data written to standard error, which can be very useful sometimes. However, if you are using the bash(1) shell, there is a trick you can use in order to distinguish between standard output data and standard error data. Almost all UNIX shells offer this functionality in their own way.
When using bash(1), you can redirect the standard error output to a file as follows:
$ go run stdERR.go 2>/tmp/stdError This is Standard output $ cat /tmp/stdError Please give me one argument!
Similarly, you can discard error output by redirecting it to the /dev/null device, which is like telling UNIX to completely ignore it:
$ go run stdERR.go 2>/dev/null This is Standard output
In the two examples, we redirected the file descriptor of standard error into a file and /dev/null, respectively. If you want to save both standard output and standard error to the same file, you can redirect the file descriptor of standard error (2) to the file descriptor of standard output (1). The following command shows the technique, which is pretty common in UNIX systems:
$ go run stdERR.go >/tmp/output 2>&1 $ cat /tmp/output This is Standard output Please give me one argument!
Finally, you can send both standard output and standard error to /dev/null as follows:
$ go run stdERR.go >/dev/null 2>&1