[Golang] Parse Command Line Arguments - String Variable


Pass argument from command line and used as string variable in Go program:

Makefile | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# cannot use relative path in GOROOT, otherwise 6g not found. For example,
#   export GOROOT=../go  (=> 6g not found)
# it is also not allowed to use relative path in GOPATH
export GOROOT=$(realpath ../go)
export GOPATH=$(realpath .)
export PATH := $(GOROOT)/bin:$(GOPATH)/bin:$(PATH)


INPUT=abc

default: fmt
	@go run demo.go -input=$(INPUT)

fmt:
	@go fmt demo.go
demo.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package main

import (
	"flag"
	"fmt"
)

func main() {
	arg := flag.String("input", "defaultValue", "Command line argument")
	flag.Parse()
	fmt.Println(*arg)
}

Don't forget to call flag.Parse() in your code. If you do, your variable will always be default value.


Source code tested on:

  • Ubuntu Linux 16.10
  • Go 1.7.4.

References:

[1]
[2]flag - The Go Programming Language
[3]Go by Example: Command-Line Flags
[4][Golang] Read Command-line Arguments Example