golang

OS Args Golang

If you have ever used a command-line utility, you know that there is one thing they all have in common. They all accept command-line arguments.

Arguments are one of the best ways to create parameters for programs during execution. For example, when you run the go run command, you also specify the name of the file you wish to compile. Here, the run and the name of the file are command-line arguments that tell the Go compiler what to do.

This guide will walk you through creating arguments for your Go programs.

Golang OS Package

To use command-line arguments in our program, we need to import the OS package. This package contains os.Args variable which holds command-line arguments

This variable is an array of strings and it keeps track of the arguments passed to the program. Keep in mind that the first argument is actually the name of the program.

For example:

package main
import (
    "fmt"
    "os"
)
funcmain() {
    pg_name := os.Args[0]
    fmt.Println(pg_name)
}

In the example above, we use the os.Args array to retrieve the first argument (index 0). Since the first argument is the name of the program based to the Go compiler, the resulting output is the full path to the executable of the program.

$ go run os_args.go
C:\Users\csalem\AppData\Local\Temp\go-build3770603401\b001\exe\os_args.exe
Golang Get Number of Arguments

Golang Get Number of Arguments

We can get the number of arguments passed to a program using the len() function. Since the os.Args is simply an array, the len function will return the number of elements in the array.

An example program is as shown below:

packagemain
import (
    "fmt"
    "os"
)
funcmain() {
    arg_len:= len(os.Args[1:])
    fmt.Println("Argument length: ", arg_len)

}

If we run the above code with a number of command-line arguments:

$ go run os_args.go first, second, third

We should get the total number of arguments passed to the program

Argument length: 3

NOTE: Since we know the first argument is the name of the program, we use array slicing to remove the first element and grab all other arguments after index 0.

Golang Command-Line Flags

We can define our own custom flags using the flags package. An example of a command-line flag would be -h, -l or other.

For example, MySQL cmd utility allows you to specify the username and password using the command:

mysql -u root -p

Let us implement a simple program that works as a login prompt.

package main
import (
    "flag"
    "fmt"
)
funcmain() {
    var username string
    var password string

    flag.StringVar(&username, "u", "root", "Default username: root")
    flag.StringVar(&password, "p", "mysql", "Default password: mysql")

    if username == "root" && password == "mysql" {
        fmt.Println("MySQL>")
    } else {
        fmt.Println("An Error Occourred.")
    }
}

The above simple program uses the -u and -p flag to check if the provided username and password match. If correct, we display a “MySQL” prompt and otherwise, return a message.

Once we build the program:

go build cmd_flag.go

We can run with the arguments as

./cmd_flags.exe -u root -p mysql

This should return the message in the if block as shown:

$ ./flags.exe -u root -p mysql

MySQL

Otherwise, the command should return the message in the else block.

Conclusion

In this article, we covered the basics of working the command-line arguments using the OS package. We also covered how to use command-line flags from the flags package.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list