SyntaxPilot
Courses/Go Programming/Lesson 59
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 59 of 89

Building command-line tools

CLI designos.Argsflag package (String, Int, Bool, Var, Parse)custom flag.Valuesubcommands with flag.FlagSetcobra and urfave/cli (concept)stdinstdout and stderrpiping and exit codesos/exec for running commandsreading config from environmentsignal handling with os/signalprogress output

These are the notes for Go episode 59, the first episode of the "building real things" block. Raju runs a chai stall and wants a billing tool he can run from the terminal. We start with os.Args, watch it crash on a missing word, and invent everything a real tool needs on the way: the flag package with defaults and free help, custom flags, subcommands, the three standard streams stdin, stdout and stderr, pipes and exit codes, running other programs with os/exec, settings from environment variables, and stopping cleanly on Ctrl+C with os/signal.

All outputs here are from real runs (Go 1.24.7, linux/amd64). The first lines of some programs, like // $ go build -o bill ., are the commands that were run, in order, exactly as the compiler stage in the video runs them.

Facts and sources

  • spf13/cobra README: "Cobra is used in many Go projects such as Kubernetes, Hugo, and GitHub CLI to name a few." Features listed include easy subcommand-based CLIs, "fully POSIX-compliant flags (including short & long versions)", "automatic help generation for commands and flags", "intelligent suggestions (app srver... did you mean app server?)" and generated shell autocomplete for bash, zsh, fish and powershell.
  • urfave/cli README: "a declarative, simple, fast, and fun package for building command line tools in Go", with commands and subcommands, shell completion and "no dependencies except Go standard library".
  • The flag, os, os/exec and os/signal behaviour (exit code 2 on a bad flag, exec: "lp": executable file not found in $PATH) is from the real runs below.

What a command-line tool is

A command-line interface (CLI) is a way of using a program by typing a command into a terminal (the text window where you run programs) and reading text back. A program used this way is a command-line tool: go, git, docker, kubectl and gh are all command-line tools, and the last three are written in Go.

Real-life example: ordering at a chai counter. There's no touch screen; you walk up and say "masala chai, 3 cups". The words after the program's name are its arguments; a busy stall uses an order slip with labelled boxes (Item: , Cups: , Parcel: [ ]) so nothing gets mixed up — those labelled boxes are flags.

In go build -o bill . the program is go, and build, -o, bill and . are its arguments.

os.Args: the raw words

os.Args is a []string holding every word of the command line. Index 0 is the program's own name, so the user's words start at index 1.

// $ go build -o bill .
// $ ./bill masala 3
// $ ./bill masala
// ---- main.go ----
package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    fmt.Println("os.Args:", os.Args)
    item := os.Args[1]
    qty, _ := strconv.Atoi(os.Args[2])
    fmt.Printf("%d x %s chai = ₹%d\n", qty, item, qty*20)
}

Real output:

$ go build -o bill .
$ ./bill masala 3
os.Args: [./bill masala 3]
3 x masala chai = ₹60
$ ./bill masala
os.Args: [./bill masala]
panic: runtime error: index out of range [2] with length 2

goroutine 1 [running]:
main.main()
    main.go:12 +0x19c

strconv.Atoi ("ASCII to integer") turns a string like "3" into the int 3. The second run forgot the quantity, so there was no word at index 2: a panic. And even when it works, os.Args alone has no names (order is fixed: bill 3 masala is wrong), no defaults, no type checking and no help.

The flag package

The standard flag package gives named, optional, typed inputs.

// $ go build -o bill .
// $ ./bill -item ginger -qty 3 -parcel
// $ ./bill -qty 2
// $ ./bill -qty three
// ---- main.go ----
package main

import (
    "flag"
    "fmt"
)

func main() {
    item := flag.String("item", "masala", "which chai")
    qty := flag.Int("qty", 1, "how many cups")
    parcel := flag.Bool("parcel", false, "pack to take away")
    flag.Parse() // reads os.Args[1:] into the flags

    total := *qty * 20
    if *parcel {
        total += 5 // ₹5 for the cup and lid
    }
    fmt.Printf("%d x %s chai, parcel=%v = ₹%d\n", *qty, *item, *parcel, total)
    fmt.Println("left over:", flag.Args())
}

Real output:

$ go build -o bill .
$ ./bill -item ginger -qty 3 -parcel
3 x ginger chai, parcel=true = ₹65
left over: []
$ ./bill -qty 2
2 x masala chai, parcel=false = ₹40
left over: []
$ ./bill -qty three
invalid value "three" for flag -qty: parse error
Usage of ./bill:
  -item string
        which chai (default "masala")
  -parcel
        pack to take away
  -qty int
        how many cups (default 1)
  • flag.String(name, default, help), flag.Int, flag.Bool (also Float64, Duration, Uint...) each return a pointer; read the value with *qty.
  • Nothing is filled in until flag.Parse() reads os.Args[1:].
  • -qty 3, -qty=3 and --qty 3 are all the same. A bool flag alone (-parcel) means true; turn it off with -parcel=false.
  • Flags stop at the first non-flag word or at --; flag.Args() returns what's left.
  • A bad value prints the error and a usage message (built from your help texts) and exits with code 2. -h or -help prints the same help (exit code 0).
  • flag.StringVar(&s, "item", "masala", "..."), flag.IntVar... fill a variable you already have.

A custom flag: flag.Value and flag.Var

A normal string flag given three times keeps only the last value. To collect them all, make your own flag type. Any type with these two methods is a flag.Value:

type Value interface {
    String() string   // shows the current value (used in help)
    Set(string) error // called once for every value typed
}

Register it with flag.Var(&v, name, help) (or fs.Var on a FlagSet). Set can also validate and return an error, which flag reports like any bad value.

Subcommands with flag.FlagSet

A subcommand is a command inside a command: go build, go test, git commit. Each has its own flags. A flag.FlagSet is a separate, named group of flags with its own Parse; make one per subcommand with flag.NewFlagSet(name, errorHandling).

// $ go build -o bill .
// $ ./bill add -item masala -item ginger -item elaichi
// $ ./bill total -gst 5 120 80
// $ ./bill refund
// ---- main.go ----
package main

import (
    "flag"
    "fmt"
    "os"
    "strconv"
    "strings"
)

// itemList is a custom flag: -item can be given many times.
type itemList []string

func (l *itemList) String() string     { return strings.Join(*l, ",") }
func (l *itemList) Set(v string) error { *l = append(*l, v); return nil }

func main() {
    if len(os.Args) < 2 {
        fmt.Println("usage: bill <add|total> [flags]")
        os.Exit(2)
    }
    switch os.Args[1] {
    case "add":
        fs := flag.NewFlagSet("add", flag.ExitOnError)
        var items itemList
        fs.Var(&items, "item", "an item to add (repeat it)")
        fs.Parse(os.Args[2:])
        fmt.Println("added", len(items), "items:", items.String())
    case "total":
        fs := flag.NewFlagSet("total", flag.ExitOnError)
        gst := fs.Int("gst", 0, "GST percent")
        fs.Parse(os.Args[2:])
        sum := 0
        for _, a := range fs.Args() { // the prices after the flags
            p, _ := strconv.Atoi(a)
            sum += p
        }
        fmt.Printf("total: ₹%d\n", sum+sum*(*gst)/100)
    default:
        fmt.Printf("unknown command %q\n", os.Args[1])
        os.Exit(2)
    }
}

Real output:

$ go build -o bill .
$ ./bill add -item masala -item ginger -item elaichi
added 3 items: masala,ginger,elaichi
$ ./bill total -gst 5 120 80
total: ₹210
$ ./bill refund
unknown command "refund"

flag.ExitOnError makes a bad flag print help and exit with code 2; flag.ContinueOnError returns the error to you instead (useful for testing, as in the mini project). Exit code 2 is the usual habit for "you used the tool wrongly".

Bigger tools: cobra and urfave/cli

Tools with dozens of subcommands usually use a library:

spf13/cobra urfave/cli
Style commands as a tree of structs (rootCmd.AddCommand(addCmd)) the app described as data (&cli.Command{Name, Flags, Action})
Flags POSIX-style short and long (-i, --item) flags for simple types, slices, time values
Extras automatic help, did-you-mean suggestions, shell completion shell completion, help, no dependencies beyond the standard library
Used by (README) Kubernetes, Hugo, GitHub CLI —

Shell completion means the shell fills in commands and flags when you press Tab. Both libraries are built on the same ideas as the code above; for a small tool, flag is enough.

stdin, stdout and stderr

Every program starts with three open streams:

Stream Go Real-life (Raju's stall) Used for
stdin (standard input) os.Stdin the order window data coming in: typing, a file, a pipe
stdout (standard output) os.Stdout the serving counter the results
stderr (standard error) os.Stderr the complaints book errors, warnings, progress

And when a program ends it returns an exit code: 0 means success, anything else means failure.

// $ go run .
// ---- main.go ----
package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

var price = map[string]int{"masala": 20, "ginger": 25, "elaichi": 30}

func main() {
    in := bufio.NewScanner(os.Stdin) // orders come in on stdin
    total, bad := 0, 0
    for in.Scan() {
        var item string
        var qty int
        _, err := fmt.Sscan(in.Text(), &item, &qty)
        p, ok := price[strings.ToLower(item)]
        if err != nil || !ok {
            fmt.Fprintf(os.Stderr, "skipping bad line: %q\n", in.Text()) // problems -> stderr
            bad++
            continue
        }
        fmt.Printf("%-8s x%d  ₹%d\n", item, qty, p*qty) // results -> stdout
        total += p * qty
    }
    fmt.Printf("%-13s₹%d\n", "TOTAL", total)
    if bad > 0 {
        os.Exit(1) // non-zero exit code: "something went wrong"
    }
}

Input (stdin):

masala 2
ginger 1
coffee 3
elaichi 2

Real output (stdout, then stderr):

$ go run .
masala   x2  ₹40
ginger   x1  ₹25
elaichi  x2  ₹60
TOTAL        ₹125
skipping bad line: "coffee 3"
exit status 1
  • bufio.NewScanner(os.Stdin) reads line by line; fmt.Sscan splits one line into values.
  • fmt.Fprintf(os.Stderr, ...) writes to stderr; fmt.Printf writes to stdout.
  • os.Exit(1) ends the program with exit code 1 (go run prints exit status 1). os.Exit skips deferred functions, so call it only at the very end, or make main call a run() function that returns the code (see the mini project).

Pipes and exit codes

cat orders.txt | bill > today.txt
bill < orders.txt && echo saved || echo "check the orders"
  • | (a pipe) connects one program's stdout to the next program's stdin.
  • > sends stdout into a file; < feeds a file into stdin. stderr still shows on the screen, which is why problems never go to stdout.
  • && runs the next command only if the exit code was 0; || only if it wasn't.
  • Habits: 0 ok, 1 it failed, 2 used wrongly (bad flags), 130 stopped by Ctrl+C (128 + signal 2).

Small tools that each do one job, joined with pipes, are how the terminal world works.

Environment variables and os/exec

An environment variable is a named setting the shell passes to every program it starts (PATH, HOME, BILL_GST). os.Getenv(name) returns the value or ""; os.LookupEnv(name) also returns ok, so "not set" and "set to empty" can be told apart.

os/exec runs another program: exec.Command(name, args...) builds the command; .Output() runs it and returns its stdout; .Run() just runs it; .CombinedOutput() returns stdout and stderr together.

// $ go run .
// $ BILL_GST=12 BILL_SHOP=Raju go run .
// ---- main.go ----
package main

import (
    "fmt"
    "os"
    "os/exec"
    "strconv"
)

func main() {
    shop := os.Getenv("BILL_SHOP") // "" when not set
    if shop == "" {
        shop = "Chai Point"
    }
    gst := 5 // default
    if v, ok := os.LookupEnv("BILL_GST"); ok { // ok tells set vs not set
        gst, _ = strconv.Atoi(v)
    }
    fmt.Printf("%s: ₹200 + %d%% GST = ₹%d\n", shop, gst, 200+200*gst/100)

    out, _ := exec.Command("go", "version").Output() // run a program, keep its stdout
    fmt.Printf("built with: %s", out)

    err := exec.Command("lp", "bill.txt").Run() // send the bill to a printer
    if err != nil {
        fmt.Println("printing failed:", err)
    }
}

Real output:

$ go run .
Chai Point: ₹200 + 5% GST = ₹210
built with: go version go1.24.7 linux/amd64
printing failed: exec: "lp": executable file not found in $PATH
$ BILL_GST=12 BILL_SHOP=Raju go run .
Raju: ₹200 + 12% GST = ₹224
built with: go version go1.24.7 linux/amd64
printing failed: exec: "lp": executable file not found in $PATH

PATH is the environment variable listing the folders where the system looks for programs; this machine has no lp (the printer command), and the error says exactly that.

Safety: exec.Command runs the program directly, with each argument passed separately — no shell is involved. Never build a command by pasting user input into a string for sh -c: characters like ; and | would let a user run anything (command injection).

The usual priority for settings: flag > environment variable > default in the code.

Ctrl+C: signals and os/signal

A signal is a small message from the operating system to a program. Ctrl+C makes the terminal send SIGINT (interrupt, signal 2); containers and service managers send SIGTERM (terminate) when asking a program to shut down. By default a Go program dies immediately. signal.NotifyContext gives you a context.Context (episode 51) that is cancelled when one of the listed signals arrives, so you can finish cleanly.

// $ go run .
// ---- main.go ----
package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    // ctx is cancelled when Ctrl+C (SIGINT) or SIGTERM arrives
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    go func() { // pretend the owner presses Ctrl+C after 350 ms
        time.Sleep(350 * time.Millisecond)
        syscall.Kill(os.Getpid(), syscall.SIGINT)
    }()

    for i := 1; i <= 10; i++ {
        select {
        case <-ctx.Done():
            fmt.Fprintln(os.Stderr, "\ninterrupted: saving bills 1 to", i-1)
            os.Exit(130) // 128 + 2 (SIGINT): the usual Ctrl+C exit code
        case <-time.After(100 * time.Millisecond): // printing one bill
            fmt.Fprintf(os.Stderr, "printing bills [%-10s] %d/10\n", bar(i), i)
        }
    }
    fmt.Println("all 10 bills printed")
}

func bar(n int) string {
    s := ""
    for range n {
        s += "#"
    }
    return s
}

Real output (all on stderr):

$ go run .
printing bills [#         ] 1/10
printing bills [##        ] 2/10
printing bills [###       ] 3/10

interrupted: saving bills 1 to 3
exit status 130

The goroutine plays the role of Raju pressing Ctrl+C (syscall.Kill(os.Getpid(), syscall.SIGINT) sends our own process a SIGINT). How many bills get printed before the signal can vary by one between runs. Always defer stop(): it stops catching signals, so a second Ctrl+C kills the program as usual.

Progress output

Progress goes to stderr, so bill > today.txt keeps the file clean. Real tools redraw one line with a carriage return \r (moves the cursor to the start of the line), so the bar seems to grow in place:

fmt.Fprintf(os.Stderr, "\rprinting bills [%-10s] %d/10", strings.Repeat("#", i), i)

Show progress only when a person is watching (stderr is a terminal), not when output goes to a file or another program.

Good CLI design: a checklist

  1. Do one job well; give it a short, clear name.
  2. Flags with safe defaults; -h shows help with examples.
  3. Read files named as arguments, or stdin when there are none; results to stdout; problems to stderr.
  4. Exit 0 on success, non-zero on failure (2 for misuse).
  5. Error messages say what went wrong and how to fix it (bill: unknown item "coffee" (try masala, ginger, elaichi)).
  6. Settings: flag > environment variable > default.
  7. Handle Ctrl+C: stop cleanly, never leave a half-written file.

Mini project: the chai bill tool

Build bill with:

  1. bill add -item x (repeatable) and bill total -gst 5, plus help with examples.
  2. bill total reads orders from a file name, or stdin when there is none.
  3. BILL_GST overrides the default GST; -gst overrides both.
  4. Ctrl+C stops and prints the partial total, exit code 130.
Solution
// bill: the chai stall billing tool (Go episode 59 mini project).
package main

import (
    "bufio"
    "context"
    "flag"
    "fmt"
    "io"
    "os"
    "os/signal"
    "strconv"
    "strings"
    "syscall"
)

var price = map[string]int{"masala": 20, "ginger": 25, "elaichi": 30}

type itemList []string

func (l *itemList) String() string     { return strings.Join(*l, ",") }
func (l *itemList) Set(v string) error { *l = append(*l, v); return nil }

func usage() {
    fmt.Fprintln(os.Stderr, `usage: bill <command> [flags]

commands:
  add    -item NAME (repeat)        list items and their prices
  total  [-gst N] [FILE]            total the orders in FILE, or stdin

examples:
  bill add -item masala -item ginger
  BILL_GST=12 bill total orders.txt
  cat orders.txt | bill total -gst 5 > today.txt`)
}

func main() { os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) }

// run returns the exit code, so deferred cleanup always runs and tests can call it.
func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
    if len(args) < 1 {
        usage()
        return 2
    }
    switch args[0] {
    case "add":
        fs := flag.NewFlagSet("add", flag.ContinueOnError)
        var items itemList
        fs.Var(&items, "item", "an item (repeat it)")
        if err := fs.Parse(args[1:]); err != nil {
            return 2
        }
        for _, it := range items {
            p, ok := price[it]
            if !ok {
                fmt.Fprintf(stderr, "bill: unknown item %q (try masala, ginger, elaichi)\n", it)
                return 1
            }
            fmt.Fprintf(stdout, "%-8s ₹%d\n", it, p)
        }
        return 0
    case "total":
        gstDefault := 5
        if v, ok := os.LookupEnv("BILL_GST"); ok { // env overrides the default
            n, err := strconv.Atoi(v)
            if err != nil {
                fmt.Fprintf(stderr, "bill: BILL_GST=%q is not a number\n", v)
                return 2
            }
            gstDefault = n
        }
        fs := flag.NewFlagSet("total", flag.ContinueOnError)
        gst := fs.Int("gst", gstDefault, "GST percent (default from BILL_GST)") // the flag overrides both
        if err := fs.Parse(args[1:]); err != nil {
            return 2
        }
        in := stdin
        if fs.NArg() > 0 { // a file name was given
            f, err := os.Open(fs.Arg(0))
            if err != nil {
                fmt.Fprintln(stderr, "bill:", err)
                return 1
            }
            defer f.Close()
            in = f
        }
        ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
        defer stop()
        return total(ctx, in, *gst, stdout, stderr)
    default:
        fmt.Fprintf(stderr, "bill: unknown command %q\n", args[0])
        usage()
        return 2
    }
}

func total(ctx context.Context, in io.Reader, gst int, stdout, stderr io.Writer) int {
    sc := bufio.NewScanner(in)
    sum, bad := 0, 0
    for sc.Scan() {
        if ctx.Err() != nil { // Ctrl+C: stop, but print what we have
            fmt.Fprintf(stderr, "\ninterrupted: partial total ₹%d\n", sum)
            return 130
        }
        var item string
        var qty int
        if _, err := fmt.Sscan(sc.Text(), &item, &qty); err != nil {
            fmt.Fprintf(stderr, "skipping bad line: %q\n", sc.Text())
            bad++
            continue
        }
        p, ok := price[item]
        if !ok {
            fmt.Fprintf(stderr, "skipping unknown item: %q\n", item)
            bad++
            continue
        }
        fmt.Fprintf(stdout, "%-8s x%d  ₹%d\n", item, qty, p*qty)
        sum += p * qty
    }
    withGST := sum + sum*gst/100
    fmt.Fprintf(stdout, "%-13s₹%d (+%d%% GST = ₹%d)\n", "TOTAL", sum, gst, withGST)
    if bad > 0 {
        return 1
    }
    return 0
}

Real runs:

$ ./bill add -item masala -item ginger
masala   ₹20
ginger   ₹25
$ printf 'masala 2\nginger x\nelaichi 1\n' > orders.txt
$ ./bill total orders.txt; echo "exit $?"
masala   x2  ₹40
skipping bad line: "ginger x"
elaichi  x1  ₹30
TOTAL        ₹70 (+5% GST = ₹73)
exit 1
$ cat orders.txt | BILL_GST=12 ./bill total -gst 0 > today.txt
skipping bad line: "ginger x"
$ cat today.txt
masala   x2  ₹40
elaichi  x1  ₹30
TOTAL        ₹70 (+0% GST = ₹70)
$ ./bill refund
bill: unknown command "refund"
usage: bill <command> [flags]
...

And with Ctrl+C pressed while bill total waited for more input: interrupted: partial total ₹40, exit 130. Note that the interrupt is noticed when the next line arrives (or input ends), because Scan blocks while waiting.

Why run(args, stdin, stdout, stderr) int? main stays one line, deferred cleanup (closing the file, stop()) always runs before os.Exit, and a test can call run with a strings.Reader and two bytes.Buffers.

Common mistakes (and the real messages)

Mistake What you see Why Fix
os.Args[2] without a length check panic: runtime error: index out of range [2] with length 2 a word was missing check len(os.Args), or use flags
reading *qty before flag.Parse() always the default nothing parsed yet call flag.Parse() first
a word where a number is expected invalid value "three" for flag -qty: parse error flag checks types type a number (help is printed)
errors printed to stdout warnings inside today.txt > and pipes take stdout fmt.Fprintln(os.Stderr, ...)
exit code 0 after a failure && runs the next step anyway the shell thinks it worked os.Exit(1) / return 1
os.Exit with defers pending cleanup never runs os.Exit skips defers exit at the end of main, or os.Exit(run())
a program that isn't installed exec: "lp": executable file not found in $PATH not in any PATH folder check the error, tell the user
sh -c with user input anything can run the shell interprets ; and \| exec.Command(name, args...)

Practice

  1. Make -qty reject 0 and negative numbers with a clear message.
  2. Add a -version flag that prints bill 1.0.0 and exits 0.
  3. Write a custom flag.Value for -size small|large that rejects anything else.
  4. Why should progress bars go to stderr?
Solutions

1.

if *qty < 1 {
    fmt.Fprintln(os.Stderr, "bill: -qty must be 1 or more")
    os.Exit(2)
}

2.

version := flag.Bool("version", false, "print the version and exit")
flag.Parse()
if *version {
    fmt.Println("bill 1.0.0")
    return
}

3.

type size string

func (s *size) String() string { return string(*s) }
func (s *size) Set(v string) error {
    if v != "small" && v != "large" {
        return fmt.Errorf("must be small or large")
    }
    *s = size(v)
    return nil
}

// var cup size = "small"; flag.Var(&cup, "size", "small or large")
// ./bill -size medium  ->  invalid value "medium" for flag -size: must be small or large

4. So that redirecting or piping stdout (bill > today.txt) captures only the results; the progress still shows on screen and never pollutes the file.

Quick quiz

1. The program below is run as ./bill -qty 4 -parcel. What does it print? (From the video.)

qty := flag.Int("qty", 1, "cups")
parcel := flag.Bool("parcel", false, "pack")
fmt.Println(*qty, *parcel)
flag.Parse()

A. 4 true · B. 1 false · C. 4 false · D. a compile error

Answer

B. The values are printed before flag.Parse() runs, so they still hold their defaults.

2. What is os.Args[0]?

Answer

The program's own name as it was run, e.g. ./bill.

3. Which exit code does a program stopped by Ctrl+C usually report?

Answer

130 = 128 + 2 (SIGINT is signal 2).

Interview questions

  1. os.Args vs flag? os.Args is the raw []string (index 0 = program name); flag parses named, typed options with defaults and generates help.
  2. How do you implement subcommands with the standard library? Switch on os.Args[1] and give each subcommand its own flag.NewFlagSet, parsing os.Args[2:].
  3. What is flag.Value? An interface (String() string, Set(string) error) for custom flag types, registered with flag.Var.
  4. Why separate stdout and stderr? So results can be piped or redirected while errors and progress still reach the user.
  5. What do exit codes mean? 0 success, non-zero failure; scripts use them with &&, || and if.
  6. Why is os.Exit dangerous in the middle of a program? It ends the process immediately; deferred functions don't run.
  7. How do you run an external command safely? exec.Command(name, args...) with arguments passed separately, never user input inside sh -c; check the error.
  8. How do you handle Ctrl+C in Go? signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) and stop work when ctx.Done() closes.

Glossary

Term Meaning Example
Terminal the text window where you type commands a shell prompt $
Command-line interface (CLI) using a program by typing commands and reading text go build
Command-line tool a program meant to be used from a terminal git, docker, bill
CLI design the conventions that make a tool easy to use defaults, help, exit codes
Argument a word typed after the program's name masala in bill masala 3
os.Args the command line as a []string; index 0 is the program [./bill masala 3]
strconv.Atoi converts a string to an int strconv.Atoi("3") → 3
Flag a named option -qty 3
flag package parses flags with types, defaults and help flag.Int("qty", 1, "cups")
flag.Parse reads the command line into the flags call before reading flags
flag.Args the words left after the flags prices after -gst 5
Usage message help text listing every flag printed on -h
flag.Value interface for custom flag types String(), Set(string)
flag.Var registers a custom flag fs.Var(&items, "item", "...")
Subcommand a command inside a command go test, bill add
flag.FlagSet a separate group of flags with its own Parse flag.NewFlagSet("add", ...)
cobra popular CLI library (spf13/cobra) used by Kubernetes, Hugo, GitHub CLI
urfave/cli declarative CLI library &cli.Command{...}
Shell completion the shell fills in commands on Tab bill a<Tab> → bill add
Stream a flow of bytes in or out of a program stdin
stdin standard input, data coming in os.Stdin
stdout standard output, the results os.Stdout
stderr standard error, problems and progress os.Stderr
Pipe connects one program's stdout to the next one's stdin cat orders.txt \| bill
Redirection sends a stream to or from a file > today.txt, < orders.txt
Exit code the number a program returns when it ends 0 ok, 1 failed, 2 misuse
os.Exit ends the program now with a code (skips defers) os.Exit(1)
Environment variable a named setting passed to every program BILL_GST=12
os.Getenv / os.LookupEnv read an environment variable (LookupEnv also says if it's set) os.LookupEnv("BILL_GST")
PATH the folders searched for programs exec: "lp": ... not found in $PATH
os/exec runs other programs exec.Command("go", "version").Output()
Command injection user input run as shell commands a name containing ; rm -rf
Signal a message from the OS to a program SIGINT, SIGTERM
SIGINT interrupt signal (Ctrl+C), number 2 exit code 130
SIGTERM terminate signal, a polite "shut down" sent by containers
os/signal catches signals signal.NotifyContext
signal.NotifyContext a context cancelled when a signal arrives ctx, stop := ...
Progress output status shown while work runs, on stderr [### ] 3/10
Carriage return \r moves the cursor to the start of the line redraws a progress bar

Summary

  • os.Args holds the raw words (index 0 = the program); it crashes on missing words and has no names, defaults or help.
  • The flag package gives named, typed flags with defaults and free help; flag.Var takes custom types; a FlagSet per subcommand gives go-style tools. cobra and urfave/cli do the same at scale.
  • Results to stdout, problems and progress to stderr, and the right exit code; that's what makes pipes and scripts work.
  • os/exec runs other programs (arguments separately, check the error); environment variables hold settings (flag > env > default).
  • signal.NotifyContext lets a tool stop cleanly on Ctrl+C (exit 130).

Next episode: networking with the net package: TCP and UDP, net.Listen, net.Dial, deadlines, a goroutine per connection, message framing and net/netip.