34.8 getopts: Parsing Command-Line Options in Scripts
Right, so you’ve written a bash script. It’s beautiful. It does one thing perfectly. Now you want to make it useful for other people, or for future-you at 2 AM, which means it needs to handle command-line options. You could manually parse $1, $2, etc. I’ve done it. You’ve done it. It’s a mess that quickly spirals into a nested if nightmare of checking for -- and -. Don’t do that. Bash gives you getopts, a built-in command designed specifically to save you from that particular brand of self-flagellation. It’s not without its quirks (it’s a bash builtin, after all), but it’s the right tool for the job.