liveBook · Manning

Command-line argument

As explained in Go in Action, Second Edition

A command-line argument is a value supplied to a program when it is invoked from a command line or operating-system process launcher.

A command-line argument is a value supplied when a program starts from a terminal or operating-system process launcher. In Go, the runtime stores these values in os.Args, whose first element is the command itself; application arguments begin at os.Args[1]. section 2.7.1

Use arguments to make a program operate on caller-selected values:

  • Check len(os.Args) before indexing so a missing required argument produces a clear error instead of an invalid access. section 2.7
  • Read the selected value from os.Args[1] and pass it to the operation, such as os.ReadFile. section 2.7.1
  • Use the flag package when options need names, types, defaults, help, or parsing; retrieve remaining positional arguments with flag.Args(). section 10.2

Selecting a file at startup

A word-counting program can accept any filename instead of being tied to words.txt. It checks for an argument, reads os.Args[1], splits the contents into fields, and prints the word count. A richer CLI can instead parse flags and require input and output filenames as positional arguments. section 2.7 section 10.2

Listing 2.30 Altering main.go to take a filename as an argument
package main

import (
	"fmt"
	"log"
	"os"
	"strings"
)

func main() {
	if len(os.Args) < 2 {
		log.Println("need to provide filename!")
		os.Exit(1)
	}

	fileContents, err := os.ReadFile(os.Args[1])
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}

	words := strings.Fields(string(fileContents))

	fmt.Println("Found", len(words), "words")
}

Runnable Go listing showing argument validation, filename selection, file reading, and error handling. section 2.7

How Go in Action, Second Edition covers it

How deep it goes
Explains os.Args indexing and validation, then extends the treatment to typed flags and remaining positional arguments.
Examples
Demonstrates filename-based word counting and a JSON/XML conversion tool accepting input and output files.
What it assumes
Assumes basic Go programs and imports while teaching os.Args and flag-based argument processing directly.
What you can do after
Build it from scratch by accepting, validating, parsing, and applying command-line values in Go programs.
How it connects
Connects command-line arguments with os.Args, the flag package, positional arguments, file operations, and CLI architecture.

Also explained in

Compare how 14 books explain command-line argument →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.