Golang : Get command line arguments
Basically there are two ways to get arguments from the command line in Go.
The first way is via the flag
package
flag.go
package main
import (
"flag"
"fmt"
)
func main() {
flag.Parse() // get the arguments from command line
arg := flag.Arg(0) // get the source directory from 1st argument
fmt.Println("The first argument is " + arg)
}
the output :
go run flag.go here
The first argument is here
go run flag.go there
The first argument is there
The second way is via the os
package
osarg.go
package main
import (
"os"
"fmt"
)
func main () {
if len(os.Args) != 3 {
fmt.Printf("Usage : %s argument1 argument2 \n ", os.Args[0]) // return the program name back to %s
os.Exit(1) // graceful exit
}
fmt.Println("First argument is : " + os.Args[1] + "\n")
fmt.Println("Second argument is : " + os.Args[2] + "\n")
}
Ok, this should cover the needs to get arguments from command line. Did I miss anything ? Leave your comment below.
See also : Golang : Check if a directory exist or not
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.9k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+9.2k Golang : Generate random Chinese, Japanese, Korean and other runes
+17.2k Golang : How to tell if a file is compressed either gzip or zip ?
+15.3k Golang : invalid character ',' looking for beginning of value
+18.8k Golang : Read input from console line
+9.8k Golang : Function wrapper that takes arguments and return result example
+6k Golang : Dealing with backquote
+5k Golang : PGX CopyFrom to insert rows into Postgres database
+12.6k Golang : Pass database connection to function called from another package and HTTP Handler
+16.3k Golang : Find out mime type from bytes in buffer