NASutils Knowledge BaseUnofficialPolski

Go · lesson 18 of 30 · Data, functions and the command lineRead options

The package flag reads -limit 95 and -quiet; flag.Arg gives one of the other arguments.

Programming on the NAS › Go in 30 lessons

18-flags.go Download 18-flags.go

package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	limit := flag.Int("limit", 90, "percent that counts as full")
	quiet := flag.Bool("quiet", false, "print nothing, set the exit code")
	flag.Parse()

	if flag.NArg() != 1 {
		fmt.Fprintln(os.Stderr, "usage: 18-flags [-limit N] [-quiet] NAME")
		os.Exit(2)
	}
	used := 93
	if !*quiet {
		fmt.Printf("%s: %d percent, limit %d\n", flag.Arg(0), used, *limit)
	}
	if used >= *limit {
		os.Exit(1)
	}
}

Terminal

$ ./18-flags media; echo "exit code $?"
media: 93 percent, limit 90
exit code 1
$ ./18-flags -limit 95 media; echo "exit code $?"
media: 93 percent, limit 95
exit code 0
$ ./18-flags -quiet media; echo "exit code $?"
exit code 1

Exercise

Add -unit with GiB or TiB.

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.