1. 程式人生 > >How to access command line arguments in Golang > LinxLabs

How to access command line arguments in Golang > LinxLabs

You need a ‘golang’ environment in Linux to try the example. I’ve explained how to install ‘golang’ in this blog post

In this article, we will see how to access command line arguments from a golang program

We will use the variable ‘Args’ from the package ‘os ‘ (https://golang.org/pkg/os/#pkg-variables)

Let’s execute below code and examine the output

package main

import (
"fmt"
"os"
)

func main() {
fmt.Printf("%T\n", os.Args)
fmt.Println(os.Args)
}

[email protected]:~/.../Golang-Tutor> go build args.go
[email protected]:~/.../Golang-Tutor> ./args ls -lrt abc 1234
[]string
[./args_sample ls -lrt abc 1234]
[email protected]:~/.../Golang-Tutor>

os.Args is a string slice and it holds all the command line arguments including executed command

You may extract each arguments using an index like os.Args[0] , os.Args[1] etc..

To iterate through the arguments we can use ‘for’ loop along with ‘range’; which will return two values; index and value of the index

Let’s modify above code with for loop

package main

import (
"fmt"
"os"
)

func main() {
for i, val := range os.Args {
fmt.Printf("Index [%d] = %s\n", i, val)
}
}
[email protected]:~/.../Golang-Tutor> go build args.go
[email protected]:~/.../Golang-Tutor> ./args ls -lrt abc 1234
Index [0] = ./args
Index [1] = ls
Index [2] = -lrt
Index [3] = abc
Index [4] = 1234

I hope this article is simple and easy
We will discuss more exciting topics in coming articles