Display Command-Line Tool Usage

Powerful Command-Line Applications in Go — by Ricardo Gerardi (23 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Handling Multiple Command-Line Options | TOC | Improving the List Output Forma t 👉

Command-line tools should be helpful. Sometimes the user doesn’t know how to use a tool or they don’t remember all the options, so it’s helpful if your tool displays usage information.

Another benefit of using the flag package is that it provides automatic usage information if the user gives an invalid option or specifically requests help. You don’t have to do anything special to take advantage of this behavior either. Try it out by running your program with the -h option:

​ ​$ ​​go​​ ​​build​​ ​​.​
​ ​$ ​​./todo​​ ​​-h​
​ Usage of ./todo:
​ -complete int
​ Item to be completed
​ -list
​ List all tasks
​ -task string
​ Task to be included in the ToDo list

You didn’t have to include the -h flag in your code; the help feature and output are provided by the flag package by default. By default, the message includes the help text you included as the third parameter when defining each flag.

In addition, the flag package displays the usage information in case the tool receives an invalid flag:

​ ​$ ​​./todo​​ ​​-test​
​ flag provided but not defined: -test
​ Usage of ./todo:
​ -complete int
​ Item to be completed
​ -list
​ List all tasks
​ -task string
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.