Golang Command Line Arguments Example [Tutorial]

It is possible to pass parameters or arguments to a program's main function using command-line arguments. We can use this technique in Go to pass parameters to our programs.

There is an array called "Args" in the os Golang package. All of the command-line arguments given are contained in the array of strings called Args:

Advertisement

var Args []string: Args hold the command-line arguments, starting with the program name.

 

Example 1: Reading first argument from command line

Here is a basic example of passing the first argument to the program:

package main
 
import (
    "os"
    "fmt"
)
 
func main() {
    firstArgs := os.Args[0]
	//print out the first argument``
    fmt.Println(firstArgs)
}

Output: If we run "go run args.go"

C:\Users\nguye\AppData\Local\Temp\go-build1687041230\b001\exe\args.exe

As you can see, the application name and the whole path are displayed. In essence, you may refer to this as os.filepath output. The program name will also print if you run it with a few random arguments.

 

Example 2: Read multiple arguments from command line

Here is a basic example of reading arguments from command line:

package main
  
import (
    "fmt"
    "os"
)
  
func main() {
    programName := os.Args[0]
	secondArg := os.Args[1]
    fourthArg := os.Args[3]
    allArgs := os.Args[1:]
  
    fmt.Println(programName)
    fmt.Println(secondArg)
    fmt.Println(fourthArg)
    fmt.Println(allArgs)
}

Output:

Advertisement

You can see that if the iteration exceeds length of arguments list, the error will appear.

 

Example 3: Get the number of CLI arguments

Here is an example of getting the number of CLI arguments:

package main
 
import (
    "fmt"
    "os"
)
 
func main() {
	// do not count the default arg
    argLength := len(os.Args[1:])
    fmt.Printf("Argument array length is %v", argLength) 
}

Output: If we run "go run .\args.go first second third "

Argument arralength is 3

 

Example 4: Using flag package to implement custom CLI arguments

To implement flags, we will use a package called flag. With the help of StringVar() function, we can assign arguments to a variable in our program:

flag: Package flag implements command-line flag parsing.

func StringVar(p *string, name string, value string, usage string): StringVar defines a string flag with a specified name, default value, and usage string. The argument p points to a string variable in which to store the value of the flag.

Here is an example of using flag and os to implement command-line flag parsing:

package main
import (
    "flag"
    "fmt"
)
 
func main() {
    // variables declaration  
    var userName string    
    var password string      
 
    flag.StringVar(&userName, "u", "default user name", "Enter your username")
    flag.StringVar(&password, "p", "default password", "Enter your username")
 
    flag.Parse()  // after declaring flags we need to call it
 
    // check if cli params match
	fmt.Println("Your username:", userName)
	fmt.Println("Your password:", password)
}

Output:

 

Summary

The Go programming language includes the ability to handle command-line arguments built-in, much like any other programming language from the C language family. With the help of os and flag package, we can customize our programs to handle parsing flags for our command-line arguments.

 

References

https://pkg.go.dev/os
https://pkg.go.dev/flag

 

Categories GO

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X