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
+7k Golang : Get today's weekday name and calculate target day distance example
+4k Python : Find out the variable type and determine the type with simple test
+5.2k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+13.5k Golang : Parsing or breaking down URL
+4.7k Golang : Detect words using using consecutive letters in a given string
+21.1k Golang : Securing password with salt
+21.5k Golang : Set and Get HTTP request headers example
+25.6k Golang : Force your program to run with root permissions
+61.7k Golang : Convert HTTP Response body to string
+13.4k Golang : Recombine chunked files example
+29.2k Golang : Remove characters from string example
+12.4k Golang : error parsing regexp: invalid or unsupported Perl syntax