Bash scripting and getops

Did you ever write a bash script and thought it looked too clean? Yeah, me neither. Anyway, now you can make it look even worse by using getopt. As an upside, you’ll be able to read command line options from a user without having to resort to nasty hacks, like hardcoding the switch position into the argv.

getopt should be installed by default in most Linux distros, and you can even run it as a command line program. It’s quite easy to use on a bashcript. For example, something like:

while getopts "bar" opt; do
    case "$opt" in
        b) echo "Option b is set"
        a) echo "Option a is set"
        r) echo "Option r is set"

It won’t look pretty but it does get the job done. According to “man getopt” it supports things like short & long options and defaults; if you need something more complex, you should probably be using a proper language instead of a bash script.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s