Access raw command line arguments

suggest change

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: '/tmp/go-build250483369/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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents