How to add arguments from command line in Go Programs

os.Args

We can use os.Args to get arguments that typed in the command line when calling Go Programs. Note that the program’s name will be included too. Just use os.Args[1:] to get the arguments only

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
	"fmt"
	"os"
)

func main() {
	// Include the Program name
	fullArgs := os.Args

	// Get arugments only
	argsWithoutProgramName := fullArgs[1:]

	fmt.Println("With Program name: ", fullArgs)
	fmt.Println("Without Program name: ", argsWithoutProgramName)
}

Output

1
2
3
4
$ go build test.go
$ test.exe a b c d
// With Program name: [test.exe a b c d e f]
// Without Program name: [a b c d e f]

Example: Checksum Application

In this example we will use the crypto package and os.Args to verify checksum of the file we downloaded from the Internet

I will use the ubuntu-18.04.3-desktop-amd64.iso file downloaded from Ubuntu homepage.

The file has a SHA256 checksum of:

1
add4614b6fe3bb8e7dddcaab0ea97c476fbd4ffe288f2a4912cb06f1a47dcfa0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
	"crypto/sha256"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	fullArgs := os.Args
	if len(fullArgs) <= 1 {
		fmt.Println("Please specify the file's name.")
		return
	}
	if len(fullArgs) > 2 {
		fmt.Println("Too much arguments.")
		return
	}
	fname := fullArgs[1]

	fileContent, err := ioutil.ReadFile(fname)
	if err != nil {
		fmt.Println("Could not read file")
		return
	}

	h := sha256.New()
	h.Write(fileContent)
	bs := h.Sum([]byte{})
	fmt.Printf("SHA256: %x\n", bs)
}

Test:

1
2
3
$ go build checksha.go
$ checksha.exe ubuntu-18.04.3-desktop-amd64.iso
// SHA256: add4614b6fe3bb8e7dddcaab0ea97c476fbd4ffe288f2a4912cb06f1a47dcfa0