Go · lesson 26 of 30 · Tools for the NASRun a command
exec.Command names a program and its arguments, Output runs it and gives what it printed, and an error tells the exit code.
26-run-command.go Download 26-run-command.go
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
)
func main() {
out, err := exec.Command("uname", "-s").Output()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("kernel:", strings.TrimSpace(string(out)))
// the words go to the program as they are, no shell reads them
err = exec.Command("grep", "-q", "DEBUG", "nas.log").Run()
var failed *exec.ExitError
switch {
case err == nil:
fmt.Println("grep found DEBUG")
case errors.As(err, &failed):
fmt.Println("grep ended with code", failed.ExitCode())
default:
fmt.Println(err)
}
}
Terminal
$ ./26-run-command
kernel: Linux
grep ended with code 1Exercise
Run df -P -k and print its second line.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.