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/v_/ksw1dqvd59v790zk2wqf_t_80000gn/T/go-build830406166/b001/exe/raw_cmd_line_args'
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