File: basics.md

package info (click to toggle)
golang-github-urfave-cli-v3 3.3.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,676 kB
  • sloc: sh: 26; makefile: 16
file content (93 lines) | stat: -rw-r--r-- 1,696 bytes parent folder | download
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
---
tags:
  - v3
search:
  boost: 2
---

Lets add some arguments to our greeter app. This allows you to change the behaviour of
the app depending on what argument has been passed. You can lookup arguments by calling 
the `Args` function on `cli.Command`, e.g.:

<!-- {
  "args" : ["Friend"],
  "output": "Hello \"Friend\""
} -->
```go
package main

import (
	"fmt"
	"log"
	"os"
	"context"

	"github.com/urfave/cli/v3"
)

func main() {
	cmd := &cli.Command{
		Action: func(ctx context.Context, cmd *cli.Command) error {
			fmt.Printf("Hello %q", cmd.Args().Get(0))
			return nil
		},
	}

	if err := cmd.Run(context.Background(), os.Args); err != nil {
		log.Fatal(err)
	}
}
```

Running this program with an argument gives the following output

```sh-session
$ greet friend
Hello "Friend"
```

Any number of arguments can be passed to the greeter app. We can get the number of arguments
and each argument using the `Args`

<!-- {
  "args" : ["Friend", "1", "bar", "2.0"],
  "output": "Number of args : 4\nHello Friend 1 bar 2.0"
} -->
```go
package main

import (
	"fmt"
	"log"
	"os"
	"context"

	"github.com/urfave/cli/v3"
)

func main() {
	cmd := &cli.Command{
		Action: func(ctx context.Context, cmd *cli.Command) error {
			fmt.Printf("Number of args : %d\n", cmd.Args().Len())
			var out string
			for i := 0; i < cmd.Args().Len(); i++ {
				out = out + fmt.Sprintf(" %v", cmd.Args().Get(i))
			}
			fmt.Printf("Hello%v", out)
			return nil
		},
	}

	if err := cmd.Run(context.Background(), os.Args); err != nil {
		log.Fatal(err)
	}
}
```

Running this program with an argument gives the following output

```sh-session
$ greet Friend 1 bar 2.0
Number of args : 4
Hello Friend 1 bar 2.0
```