-
Notifications
You must be signed in to change notification settings - Fork 0
/
11-command-line-args.go
76 lines (60 loc) · 1.81 KB
/
11-command-line-args.go
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* command-line-args.go
* A program showing how to use command-line arguments and flags in Go
*/
package main
import (
"flag"
"fmt"
"os"
)
var str string
var num int
var help bool
func main() {
// command-line args are stored as slice in os.Args
// first argument in list is program itself
num_args := len(os.Args)
// check if received any command line arguments
if num_args < 2 {
fmt.Println(">> No args passed in")
}
// flag package provides parsing of command-line parameters
// this example we create global variables and then pass them in
// as pointers which BoolVar, StringVar and IntVar set as values
flag.StringVar(&str, "str", "default value", "text description")
flag.IntVar(&num, "num", 5, "text description")
flag.BoolVar(&help, "help", false, "Display Help")
flag.Parse()
// check if help was called explicitly
if help {
fmt.Println(">> Display help screen")
os.Exit(1)
}
fmt.Println(">> String:", str)
fmt.Println(">> Number:", num)
// last command-line argument
fmt.Println(">> Last Item:", os.Args[num_args-1])
// the os.Args will include flags for example
// go run command-line-args.go --str=Foo filename
// os.Args[1] = "--str=Foo"
// If you have flags and want just the arguments
// then after calling flag.Parse() you can call
// flag.Args which store only the args
args := flag.Args()
if len(args) > 0 {
fmt.Println(">> Flag Arg:", args[0])
}
}
// $ go run command-line-args.go
// >> No args passed in
// >> String: default value
// >> Number: 5
// >> Last Item: command-line-args.go
// $ go run command-line-args.go --str=Foo --num=8 filename
// >> String: Foo
// >> Number: 8
// >> Last Item: filename
// >> Flag Arg: filename
// Try passing in invalid values, invalid flags and other tests
// The flag package provides a lot to help build command-line programs