Bash getopt versus getopts

I recently reviewed someone’s bash code, and noted their use of getopt. I had always been using getopts, so was at first confused (due to syntax), then puzzled: which one is better, getopt or getopts?

Getopt is older, but is a separate binary. It tends to be pretty robust, and supports long options (i.e., you can use –foo instead of just single letter options like -f). Getopt will also re-arrange the parameters.

Getopts is newer but built into the shell. Its syntax tends to be simpler to use.

Let’s see some quick examples of usage:



And now getopts:



Getopts does seem much simpler. Let’s run both, and see what happens:

As expected, the output is the same. However, let’s make one small change: let’s put the argument first.

Whoops! Remember how re-arranged parameters while getopts didn’t? You need to put the arguments last, or getopts gets confused. getopt will actually re-arrange the parameters to put the options first, then add a ‘–’, then put the arguments. Let’s hack our script to see what happens.



And the output:

Neither method is wrong (and I’m sure there are more tweaks to each style I could do), but I think I’m going to lean towards the getopt camp. It’s a little more work, but seems a little more robust.