Skip to main content
Command-line arguments are a common way to parameterize execution of programs. For example, go run hello.go uses run and hello.go as arguments to the go program.

Accessing Arguments with os.Args

Go provides access to raw command-line arguments through the os.Args slice. The first value in this slice is always the path to the program itself, while os.Args[1:] contains the actual arguments passed to the program.
package main

import (
	"fmt"
	"os"
)

func main() {

	// `os.Args` provides access to raw command-line
	// arguments. Note that the first value in this slice
	// is the path to the program, and `os.Args[1:]`
	// holds the arguments to the program.
	argsWithProg := os.Args
	argsWithoutProg := os.Args[1:]

	// You can get individual args with normal indexing.
	arg := os.Args[3]

	fmt.Println(argsWithProg)
	fmt.Println(argsWithoutProg)
	fmt.Println(arg)
}

Running the Program

To experiment with command-line arguments, it’s best to build a binary with go build first:
go build command-line-arguments.go
./command-line-arguments a b c d
[./command-line-arguments a b c d]
[a b c d]
c
The first element of os.Args is always the program name. Use os.Args[1:] to access only the user-provided arguments.

Key Points

os.Args Structure

The first element (os.Args[0]) is the program path, followed by the actual arguments.

Array Indexing

Access individual arguments using standard slice indexing like os.Args[3].
Make sure to check the length of os.Args before accessing specific indices to avoid index out of bounds errors.

Next Steps

For more advanced command-line processing with named flags and options, see Command Line Flags.

Build docs developers (and LLMs) love