Essential Go Parse command line arguments  Suggest an edit

Raw access to command line arguments

If flag package or a third-party library doesn’t provide the features you want, you can parse the arguments yourself.

func main() {
	fmt.Printf("Name of executable: '%s'\n", os.Args[0])
	args := os.Args[1:]
	for i, arg := range args {
		fmt.Printf("Arg %d, value: '%s'\n", i, arg)
Name of executable: '/var/folders/2k/p2_4052s70vd5_cfdm0k0l740000gn/T/go-build482523970/b001/exe/main'
Arg 0, value: '-echo'
Arg 1, value: 'echo-arg'
Arg 2, value: 'additional'
Arg 3, value: 'arg'

The above output is a result of go run $file -echo echo-arg additional arg.

Raw arguments

Raw command-line arguments can be accessed via []string slice os.Args.

First element is name of the executable.

Remaining elements are cmd-line arguments as decoded by OS shell.

On Windows cmd-line arguments are a single UTF-16 Unicode string.

Go runtime converts them to UTF-8 string and splits into separate arguments to unify handling across different operating systems.

  ↑ ↓ to navigate     ↵ to select     Esc to close