Creating helpful command line applications in ruby
Jan 14, 2016
So what makes a good and helpful command line application? I think these three point are important:
easy to use
helpful
play well with others
Bash is commonly used to write command line apps, but I can never shrug of the feeling of shame of writing a bash script with more than 30 lines.
That’s why I’m shaking things up here and showing how to use ruby instead. I’ll be using the optparse gem so you need to do a gem install optparse
before trying out the shown examples.
A bad example
This is how a bad command line application looks like (it will try to take a backup of a mysql database):
This is bad for a various of reasons. First of all the user will have no idea how to run this script without looking at the source code. Second, the script doesn’t have input validation, it will gladly just take one parameter, even though 4 parameter is required. Third, using the system command will not give the user any feedback.
A better example with optparse
First thing we’ll create an empty hash that will store all our options. In the OptionParser block we’ll assign both flags and switches making the user able to execute the utility as they choose. The opt.banner will be printed when no arguments was passed to the program or wrong number of argument, making the program user-friendly.
Running the program with no arguments will look like this:
And running the program with the correct arguments: