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
+32.9k Delete a directory in Go
+15.6k Golang : How to login and logout with JWT example
+8.7k Golang : Gorilla web tool kit schema example
+6.3k Golang : Handling image beyond OpenCV video capture boundary
+5k Golang : Issue HTTP commands to server and port example
+32.3k Golang : Copy directory - including sub-directories and files
+13.4k Golang : Get user input until a command or receive a word to stop
+18.2k Golang : Read binary file into memory
+13.4k Facebook PHP getUser() returns 0
+6.4k Golang : Calculate diameter, circumference, area, sphere surface and volume
+8.7k Golang : Random integer with rand.Seed() within a given range
+8.4k Golang : Another camera capture GUI application with GTK and OpenCV