Introduction
Command line arguments are a way to pass information into a program when it is executed. In Go, you can access command line arguments using the os
package. In this chapter, you will learn how to read and use command line arguments in Go programs.
Accessing Command Line Arguments
The os
package provides the os.Args
variable, which is a slice of strings that holds the command line arguments passed to the program. The first element, os.Args[0]
, is the name of the program, and the subsequent elements are the arguments passed to the program.
Example
Example:
package main
import (
"fmt"
"os"
)
func main() {
// Print the command line arguments
fmt.Println("Command Line Arguments:")
for i, arg := range os.Args {
fmt.Printf("Arg %d: %s\n", i, arg)
}
}
If you save this program as args.go
and run it from the command line like this:
go run args.go first second third
You will get the following output:
Command Line Arguments:
Arg 0: /tmp/go-buildxxxxx/b001/exe/args
Arg 1: first
Arg 2: second
Arg 3: third
Parsing Command Line Arguments
For more advanced command line parsing, you can use the flag
package. The flag
package allows you to define flags (options) that can be passed to the program and automatically parses them.
Example Using the flag
Package
Example:
package main
import (
"flag"
"fmt"
)
func main() {
// Define flags
name := flag.String("name", "World", "a name to say hello to")
age := flag.Int("age", 0, "your age")
verbose := flag.Bool("v", false, "verbose mode")
// Parse the flags
flag.Parse()
// Use the flag values
fmt.Printf("Hello, %s!\n", *name)
if *age > 0 {
fmt.Printf("You are %d years old.\n", *age)
}
if *verbose {
fmt.Println("Verbose mode is enabled.")
}
// Print remaining command line arguments
fmt.Println("Remaining arguments:", flag.Args())
}
If you save this program as flags.go
and run it from the command line like this:
go run flags.go -name=Alice -age=30 -v extra1 extra2
You will get the following output:
Hello, Alice!
You are 30 years old.
Verbose mode is enabled.
Remaining arguments: [extra1 extra2]
Handling Missing or Invalid Arguments
You can handle missing or invalid arguments by checking the parsed flag values and providing appropriate feedback to the user.
Example with Error Handling
Example:
package main
import (
"flag"
"fmt"
"os"
)
func main() {
// Define flags
name := flag.String("name", "", "a name to say hello to")
age := flag.Int("age", 0, "your age")
// Parse the flags
flag.Parse()
// Check required flags
if *name == "" {
fmt.Println("Error: -name flag is required")
flag.Usage()
os.Exit(1)
}
if *age <= 0 {
fmt.Println("Error: -age flag must be greater than 0")
flag.Usage()
os.Exit(1)
}
// Use the flag values
fmt.Printf("Hello, %s!\n", *name)
fmt.Printf("You are %d years old.\n", *age)
}
If you save this program as validate.go
and run it from the command line without the required flags:
go run validate.go
You will get the following output:
Error: -name flag is required
Usage of /tmp/go-buildxxxxx/b001/exe/validate:
-age int
your age
-name string
a name to say hello to
exit status 1
Conclusion
Command line arguments in Go can be accessed using the os
package for simple scenarios or the flag
package for more complex parsing. By understanding how to read, parse, and validate command line arguments, you can create more flexible and user-friendly command line applications in Go. Whether you need to handle simple arguments or complex flags, these tools provide the functionality you need to manage command line input effectively.