32. Command-line arguments
The programs in Chapter 31 had their file names written into the code. To count the lines of a different file, you had to edit the program. Real tools do not work like that. You tell them what to do when you run them:
.\wc.exe notes.txt
Everything after the program's name is a command-line
argument. This chapter shows how a Go program reads them, how
it reports problems the way other tools do, how it reads text piped into
it from another command, and how to turn it into a .exe you
can run without go run.
os.Args
os.Args is a slice of strings holding the words typed on
the command line. This is exercises/32/01-args.go, inside
main:
fmt.Println("Program:", filepath.Base(os.Args[0]))
fmt.Println("Arguments:", len(os.Args)-1)
for i, arg := range os.Args[1:] {
fmt.Printf("%d: %s\n", i+1, arg)
}Run it with three arguments after the file name:
go run exercises/32/01-args.go hello "two words" 42
Output:
Program: 01-args.exe
Arguments: 3
1: hello
2: two words
3: 42
os.Args[0]is always the program itself.go runbuilds the program into a folder of its own, so the full path is long.filepath.Basefrom Chapter 31 keeps only the last part.- The arguments you typed start at
os.Args[1].os.Args[1:]is the slice of just those, as in Chapter 22. - The terminal splits the line at spaces. Quotes keep words together:
"two words"arrives as one argument, without the quotes. - Every argument is a string, even
42. To use it as a number, convert it withstrconv.Atoi, and check the error, as with anything a user types.
With go run, the arguments for your program come after
the file name. Anything before the file name is for go
itself.
Standard output, standard error, and exit codes
Every program starts with two places to write text. Standard
output (stdout) is for the program's results.
fmt.Println writes there. Standard error
(stderr) is for messages about problems. In the terminal both show up in
the same window, so they look the same. The difference appears when you
send the results somewhere else.
Every program also ends with an exit code: a whole
number it hands back to whoever started it. 0 means
success. Anything else means something went wrong. Scripts and other
programs check it to decide what to do next. main returning
normally gives 0. os.Exit(1) ends the program
at once with code 1.
This is exercises/32/02-greet.go:
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: greet NAME...")
os.Exit(1)
}
for _, name := range os.Args[1:] {
fmt.Printf("Hello, %s!\n", name)
}
}fmt.Fprintln(os.Stderr, ...) is the
fmt.Fprintln from Chapter 31, writing to standard error
instead of a file. Two runs:
go run exercises/32/02-greet.go Keiko Arif
Hello, Keiko!
Hello, Arif!
go run exercises/32/02-greet.go
usage: greet NAME...
exit status 1
The line exit status 1 is not from your program.
go run prints it when the program ends with a code that is
not 0. A usage line like
usage: greet NAME... is the usual way for a tool to say how
to run it. Words in capitals stand for something you fill in, and
... means "one or more".
Most tools follow these rules, and yours should too:
| Exit code | Meaning |
|---|---|
0 |
It worked. |
1 |
It failed: a file was missing, the input was bad. |
2 |
It was run the wrong way: an unknown flag, a missing argument. |
In PowerShell, $LASTEXITCODE holds the exit code of the
last program. With go run it is always 1 after
a failure, because it is the exit code of go itself. The
exit status line shows your program's real code. Once you
build an .exe, at the end of this chapter,
$LASTEXITCODE shows the program's own code.
os.Exit ends the program at once. Deferred calls do
not run.
exercises/32/03-exit-skips-defer.go shows it:
func main() {
defer fmt.Println("This line never prints")
fmt.Println("Stopping with exit code 3")
os.Exit(3)
}Stopping with exit code 3
exit status 3
A deferred Flush or Close would be skipped
too, and the end of a file could be lost. Call os.Exit only
in main, after the work is finished. Chapter 33 shows a
tidy way to arrange that.
Flags
Positional arguments, like the names above, are fine for a list of
things. For options, settings that change how the
program works, tools use flags: arguments that start
with -, like -times 3. The flag
package reads them for you. This is
exercises/32/04-flags.go, inside main:
name := flag.String("name", "World", "who to greet")
times := flag.Int("times", 1, "how many times to greet")
shout := flag.Bool("shout", false, "greet in capital letters")
flag.Parse()
greeting := fmt.Sprintf("Hello, %s!", *name)
if *shout {
greeting = strings.ToUpper(greeting)
}
for range *times {
fmt.Println(greeting)
}Each of flag.String, flag.Int and
flag.Bool takes three things: the flag's name without the
-, its default value, and a short description for the help
text. Each returns a pointer, as in Chapter 27. At this
point the flags have not been read yet, so there is nothing to return
but a place where the value will be. flag.Parse() reads
os.Args and fills in those places. After it,
*name is the value. Some runs:
go run exercises/32/04-flags.go
Hello, World!
go run exercises/32/04-flags.go -name Keiko -times 2 -shout
HELLO, KEIKO!
HELLO, KEIKO!
go run exercises/32/04-flags.go -name=Arif
Hello, Arif!
A flag's value can follow after a space or after =. A
bool flag is different: -shout alone means
true, and to give a value you must use =, as
in -shout=false.
The flag package also writes the help for you. Run the
program with -h:
go run exercises/32/04-flags.go -h
Usage of C:\Users\Keiko\AppData\Local\go-build\...\04-flags.exe:
-name string
who to greet (default "World")
-shout
greet in capital letters
-times int
how many times to greet (default 1)
And it handles mistakes. An unknown flag, or a value of the wrong type, prints the problem and the same help, and exits with code 2:
go run exercises/32/04-flags.go -nmae Keiko
flag provided but not defined: -nmae
Usage of C:\Users\Keiko\AppData\Local\go-build\...\04-flags.exe:
...
exit status 2
go run exercises/32/04-flags.go -times abc
invalid value "abc" for flag -times: parse error
...
All of this goes to standard error. Your code after
flag.Parse() only ever sees good values.
Flags and other arguments together
After the flags, a command line can carry ordinary arguments, such as
file names. flag.Args() returns the arguments left over
after the flags, as a slice of strings, and flag.NArg()
says how many there are. flag.Arg(0) is the first of
them.
The help above starts with a long path. flag.Usage is
the function the flag package calls to print help, and you
can replace it with your own. This is
exercises/32/05-usage.go:
func usage() {
fmt.Fprintln(os.Stderr, "usage: greet [flags] NAME...")
fmt.Fprintln(os.Stderr, "Greets each NAME. Flags:")
flag.PrintDefaults()
}
func main() {
flag.Usage = usage
shout := flag.Bool("shout", false, "greet in capital letters")
flag.Parse()
if flag.NArg() == 0 {
usage()
os.Exit(2)
}
for _, name := range flag.Args() {
greeting := fmt.Sprintf("Hello, %s!", name)
if *shout {
greeting = strings.ToUpper(greeting)
}
fmt.Println(greeting)
}
}flag.Usage = usage stores your function, by name with no
(), as Chapter 24 did with slices.SortFunc.
flag.PrintDefaults() prints the list of flags, the bottom
part of the help. In a usage line, [flags] in square
brackets means "optional".
go run exercises/32/05-usage.go -shout Keiko Arif
HELLO, KEIKO!
HELLO, ARIF!
go run exercises/32/05-usage.go
usage: greet [flags] NAME...
Greets each NAME. Flags:
-shout
greet in capital letters
exit status 2
Flags must come before the other arguments. The
flag package stops looking for flags at the first argument
that is not one:
go run exercises/32/05-usage.go Keiko -shout
Hello, Keiko!
Hello, -shout!
Subcommands
Bigger tools do several jobs, picked by the first argument:
go run, go build and go version
are all the one program go. Each job is a
subcommand, and each can have flags of its own.
exercises/32/06-notes.go is a small notes tool with two
subcommands, add and list. It keeps the notes
in notes.txt, one per line.
main picks the subcommand with a switch on
os.Args[1], and hands the rest of the arguments to a
function for that job:
func main() {
if len(os.Args) < 2 {
usage()
os.Exit(2)
}
var err error
switch os.Args[1] {
case "add":
err = addCommand(os.Args[2:])
case "list":
err = listCommand(os.Args[2:])
default:
fmt.Fprintf(os.Stderr, "unknown command %q\n", os.Args[1])
usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}The command functions return an error instead of printing it, and
main prints it in one place. Each command parses its own
flags with a flag set, a separate group of flags made
by flag.NewFlagSet:
func listCommand(args []string) error {
flags := flag.NewFlagSet("list", flag.ExitOnError)
last := flags.Int("last", 0, "show only the last n notes (0 shows all)")
flags.Parse(args)
notes, err := readNotes()
if err != nil {
return err
}
...
}A flag set has the same methods as the flag package:
Int, String, Bool,
Parse, Args, NArg. The first
argument to NewFlagSet is the name shown in its help.
flag.ExitOnError says what to do with a bad flag: print the
problem and the help, and exit with code 2, as the plain
flag package does. That is why the error from
flags.Parse is not checked: with ExitOnError,
it never returns one.
addCommand joins the arguments into one line with
strings.Join(words, " "), which puts the second argument
between the words, and appends the line to the file with
os.OpenFile as in Chapter 31. readNotes reads
the lines with a scanner, and a missing file means no notes yet. A
session:
go run exercises/32/06-notes.go add Buy rice
Added: Buy rice
go run exercises/32/06-notes.go add "Call Arif"
Added: Call Arif
go run exercises/32/06-notes.go add Water the plants
Added: Water the plants
go run exercises/32/06-notes.go list -last 2
2. Call Arif
3. Water the plants
go run exercises/32/06-notes.go add
error: add needs the text of the note
exit status 1
go run exercises/32/06-notes.go delete 1
unknown command "delete"
usage:
notes add TEXT... add a note
notes list [-last N] show the notes
exit status 2
Add a subcommand count to
exercises/32/06-notes.go that prints how many notes there
are. Add it to the usage text too.
Reading standard input
Chapter 15 read what the user typed from os.Stdin,
standard input. Standard input does not have to be the
keyboard. In a pipe, written with |, the
output of one command becomes the standard input of the next:
Get-Content exercises/31/poem.txt | go run exercises/32/07-wc.go
Get-Content is the PowerShell command that prints a
file. Here its output never reaches the screen: it goes into the
program's standard input. A tool that reads standard input when it is
given no file names works in pipes, which is how small tools get
combined into bigger jobs.
exercises/32/07-wc.go counts lines, words and
characters, like a tool called wc ("word count") that Linux
and macOS have. Here is the counting function:
type counts struct {
lines int
words int
chars int
}
// count reads f line by line. Characters are counted without the line endings.
func count(f *os.File) (counts, error) {
var c counts
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
c.lines++
c.words += len(strings.Fields(line))
c.chars += utf8.RuneCountInString(line)
}
return c, scanner.Err()
}The parameter has the type *os.File: an open file, which
is what os.Open gives back. os.Stdin has the
same type, so count works on both.
strings.Fields from Chapter 14 splits a line into words,
and utf8.RuneCountInString from Chapter 12 counts
characters, not bytes.
main reads standard input when there are no file names,
and otherwise counts each file:
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() == 0 {
c, err := count(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, "wc:", err)
os.Exit(1)
}
fmt.Printf("%6d %6d %6d\n", c.lines, c.words, c.chars)
return
}
exitCode := 0
for _, name := range flag.Args() {
c, err := countFile(name)
if err != nil {
fmt.Fprintln(os.Stderr, "wc:", err)
exitCode = 1
continue
}
fmt.Printf("%6d %6d %6d %s\n", c.lines, c.words, c.chars, name)
}
os.Exit(exitCode)
}A file that cannot be opened does not stop the others. Its error goes
to standard error, and the exit code at the end is 1, so
that whoever ran the tool knows that not everything worked. Starting an
error message with the tool's name, as in wc:, is a habit
of command-line tools: when several are combined, you can see which one
complained.
Opening and closing is in a function of its own,
countFile:
func countFile(name string) (counts, error) {
f, err := os.Open(name)
if err != nil {
return counts{}, err
}
defer f.Close()
return count(f)
}Why not open the file in the loop in main, with
defer f.Close() there? Because a deferred call waits for
its function to return, not for the loop round to end. Every
file would stay open until main finished. With a thousand
files, that is a thousand open files at once, and the system may refuse
to open more. A small function per file closes each one as soon as it is
done.
Three runs, with a file, with a file that does not exist, and in a pipe:
go run exercises/32/07-wc.go exercises/31/poem.txt
7 39 192 exercises/31/poem.txt
go run exercises/32/07-wc.go exercises/31/poem.txt nothing.txt
7 39 192 exercises/31/poem.txt
wc: open nothing.txt: The system cannot find the file specified.
exit status 1
Get-Content exercises/31/poem.txt | go run exercises/32/07-wc.go
7 39 192
Run it with no file and no pipe, and it waits for you to type. Type a few lines, then press Ctrl + Z and Enter to end the input, as in Chapter 21.
Building a .exe
go run compiles the program, runs it, and throws the
compiled copy away, as Chapter 07 explained. To keep it, use
go build:
go build -o wc.exe exercises/32/07-wc.go
-o wc.exe names the output file. Nothing is printed when
it works, and wc.exe appears in go-work. It is
a complete program: you can copy it to another Windows computer and run
it there, with no Go installed. Run it with .\ in front,
which tells PowerShell to look in the current folder:
.\wc.exe exercises\31\poem.txt
7 39 192 exercises\31\poem.txt
Get-Content exercises\31\poem.txt | .\wc.exe
7 39 192
Without the .\, PowerShell does not look in the current
folder, and says that the term wc.exe is not
recognized.
Now the exit code is the program's own, and stdout and stderr can be
told apart. > sends standard output to a file. Standard
error still comes to the screen:
.\wc.exe exercises\31\poem.txt nothing.txt > counts.txt
wc: open nothing.txt: The system cannot find the file specified.
$LASTEXITCODE
1
counts.txt holds the line for the poem, and the error
did not end up in it. That is the whole point of standard error:
problems stay visible even when the results go somewhere else.
After a change to the code, build again. The .exe is a
copy of the program at the moment you built it. Chapter 47 covers
building properly: version numbers, smaller files, and building for
Linux.
Build exercises/32/05-usage.go as
greet.exe. Run .\greet.exe -h, and see that
the help no longer starts with a long path, because your own
usage prints it.
Homework
Homework starters are in exercises/32/homework/. Each
one runs as it is, with a placeholder. Error messages go to standard
error, and the exit codes follow the table above.
Problem 1 — Repeat
Open exercises/32/homework/01-repeat.go. Add a flag
-n (an int, default 2). Join the words after the flags with
spaces, and print that line n times. With no words, print a
usage line and exit with code 2. If n is below 1, print an
error and exit with code 2.
Problem 2 — Sum
Open exercises/32/homework/02-sum.go. Add up the whole
numbers given as arguments, and print the total: 3 4 5
prints 12. With no arguments, print a usage line and exit
with code 2. If an argument is not a whole number, print a message that
names it and exit with code 1.
Problem 3 — An upper-case filter
Open exercises/32/homework/03-upper.go. Read standard
input line by line, and print each line in capital letters. Add a bool
flag -n that puts the line number in front of each line.
Try it in a pipe with Get-Content.
Challenge — A search tool
Open exercises/32/homework/04-search.go. Write
search [-i] WORD [FILE...], which prints every line that
contains WORD, as name:number: line. With no
file, it reads standard input. -i ignores upper and lower
case. It exits with 0 when a line matched, 1
when none did, and 2 for wrong usage or a file it could not
read. Build it as search.exe and try it on several files at
once.
Stuck or done? Open the homework solutions page.