How to Access Command-Line Arguments in Go
Created
Modified
Using os.Args Variable
You can access the command-line arguments using the os.Args variable.
Note that the first value in this slice is the path to the program, and os.Args[1:] holds the arguments to the program. For example,
package main
import (
"fmt"
"os"
)
// Command-Line Arguments
// go run main.go -path=/home
func main() {
fmt.Println(os.Args[0])
fmt.Println(os.Args[1])
}
./main --path=/home
Using flag Package
Package flag implements command-line flag parsing.
Go provides a `flag` package supporting basic command-line flag parsing. We'll use this package to implement our example command-line program.
See the following example:
package main
import (
"flag"
"fmt"
)
// Command-Line Arguments
// go run main.go -path=/home -n=10 -svar=ss
func main() {
pathPtr := flag.String("path", "tmp", "Path")
nPtr := flag.Int("n", 42, "an int")
var svar string
flag.StringVar(&svar, "svar", "bar", "a string var")
flag.Parse()
fmt.Println(*pathPtr)
fmt.Println(*nPtr)
fmt.Println(svar)
fmt.Println(flag.Args())
}
/home 10 ss []