Advertisement

The os package in Golang provides various functions in order to deal with the operating system in a platform-independent manner. Command-Line Arguments in Golang are available to a program in a variable named Args that is part of the os package. The args variable can be accessed using ‘os.Args‘.

os.Args variable is a slice of strings. The First element of os.Args, os.Args[0], is the name of the command itself. The other elements are the arguments that were presented to the program when it started execution.

A slice expression of the form s[m:n] yields a slice that refers to elements m through n-1, so the elements for our use will be:

os.Args[1:len(os.Args)]

This code can also be written as:

os.Args[1:]

package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println(os.Args[1])
}

go run main.go hello

Output:

hello

Unix echo Using Golang Command-Line Arguments

You must have thought some time about how the UNIX echo command works. we write echo and then the string which we want to print.

Let’s implement UNIX echo in Golang using Command-Line Arguments.

package main

import (
	"fmt"
	"os"
)

func main() {
	var str, temp string
	for i := 1; i < len(os.Args); i++ {
		str += temp + os.Args[i]
		temp = " "
	}
	fmt.Println(str)
}

go run main.go Hello Golang! How are you?

Output:

Hello Golang! How are you?

Performing sum

The CLI arguments in Golang are always passing as a string and thus we need to convert the string to a corresponding integer value then the addition operation can take place.

The conversion from string to an integer value is done by the strconv package’s parseInt function.

package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	var sum int64
	for i := 1; i < len(os.Args); i++ {
		n, _ := strconv.ParseInt(os.Args[i], 10, 0)
		sum += n
	}
	fmt.Printf("%T %v", sum, sum)
}

go run main.go 10 20 30

Output:

int64 60

About Author
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top