Linux Tweaks, HowTo's and Reviews

I've always wanted to know how to create command line options for my Bash scripts. After some research I found there are two functions available to handle this; getopt and getopts. I'm not going to get into the debate about which one is better. getopts is a shell builtin and seems a little easier to implement than getopt, so I'll go with that for now.

bash getopts

I started out just trying to figure out how to process command line switches in my scripts. Eventually, I added some other useful functionality that makes this a good starting template for any interactive script. I've also included a help function with text formatting to make it a little easier to read.

Rather than go into a lengthy explanation of how getopts works in bash, I think it's simpler to just show some working code in a script.

Paste the above text into a text editor and then save it somewhere in your executable path. I chose to call the script options and I saved it under /home/linerd/bin. Once you save it, make sure to make it executable.

chmod +x ~/bin/options

Now you can run the script. Try running it with the -h switch to show the help information.

options -h

Now try running it with an unsupported option.

options -z

Finally, getopts can handle your command line options in any order. The only rule is that the file or files you are processing have to come after all of the option switches.

options -d bar -c chu -b man -a foo example1.txt example2.txt

So you can see from these examples how you can set variables in your scripts with command line options. There's more going on than just getopts in this script, but I think these are valuable additions that make this a good starting template for new scripts. If you'd like to learn more about bash getopts, you can find the documentation buried deep within the bash man page in the "Builtins" section. You can also find info in the Bash Reference Manual.

Another aspect of command-line option processing involves what I call "qualifiers." When building an application, some options might be required. Other options might be completely, well, optional. Still other options might require one or more different options to clarify or modify the behavior of the primary option. Some options might be mutually exclusive. I think that you get the idea.
While we can implement rules and program logic to enforce these "qualifiers," it might be nice to have something in a table or similar so that our application need not have pages of ad hoc code to do the work.