| 1 | --- |
| 2 | tags: |
| 3 | - v3 |
| 4 | search: |
| 5 | boost: 2 |
| 6 | --- |
| 7 | |
| 8 | Lets add some arguments to our greeter app. This allows you to change the behaviour of |
| 9 | the app depending on what argument has been passed. You can lookup arguments by calling |
| 10 | the `Args` function on `cli.Command`, e.g.: |
| 11 | |
| 12 | <!-- { |
| 13 | "args" : ["Friend"], |
| 14 | "output": "Hello \"Friend\"" |
| 15 | } --> |
| 16 | ```go |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "log" |
| 22 | "os" |
| 23 | "context" |
| 24 | |
| 25 | "github.com/urfave/cli/v3" |
| 26 | ) |
| 27 | |
| 28 | func main() { |
| 29 | cmd := &cli.Command{ |
| 30 | Action: func(ctx context.Context, cmd *cli.Command) error { |
| 31 | fmt.Printf("Hello %q", cmd.Args().Get(0)) |
| 32 | return nil |
| 33 | }, |
| 34 | } |
| 35 | |
| 36 | if err := cmd.Run(context.Background(), os.Args); err != nil { |
| 37 | log.Fatal(err) |
| 38 | } |
| 39 | } |
| 40 | ``` |
| 41 | |
| 42 | Running this program with an argument gives the following output |
| 43 | |
| 44 | ```sh-session |
| 45 | $ greet friend |
| 46 | Hello "Friend" |
| 47 | ``` |
| 48 | |
| 49 | Any number of arguments can be passed to the greeter app. We can get the number of arguments |
| 50 | and each argument using the `Args` |
| 51 | |
| 52 | <!-- { |
| 53 | "args" : ["Friend", "1", "bar", "2.0"], |
| 54 | "output": "Number of args : 4\nHello Friend 1 bar 2.0" |
| 55 | } --> |
| 56 | ```go |
| 57 | package main |
| 58 | |
| 59 | import ( |
| 60 | "fmt" |
| 61 | "log" |
| 62 | "os" |
| 63 | "context" |
| 64 | |
| 65 | "github.com/urfave/cli/v3" |
| 66 | ) |
| 67 | |
| 68 | func main() { |
| 69 | cmd := &cli.Command{ |
| 70 | Action: func(ctx context.Context, cmd *cli.Command) error { |
| 71 | fmt.Printf("Number of args : %d\n", cmd.Args().Len()) |
| 72 | var out string |
| 73 | for i := 0; i < cmd.Args().Len(); i++ { |
| 74 | out = out + fmt.Sprintf(" %v", cmd.Args().Get(i)) |
| 75 | } |
| 76 | fmt.Printf("Hello%v", out) |
| 77 | return nil |
| 78 | }, |
| 79 | } |
| 80 | |
| 81 | if err := cmd.Run(context.Background(), os.Args); err != nil { |
| 82 | log.Fatal(err) |
| 83 | } |
| 84 | } |
| 85 | ``` |
| 86 | |
| 87 | Running this program with an argument gives the following output |
| 88 | |
| 89 | ```sh-session |
| 90 | $ greet Friend 1 bar 2.0 |
| 91 | Number of args : 4 |
| 92 | Hello Friend 1 bar 2.0 |
| 93 | ``` |