Chapter 8. Arguing

Some scripts are meant to do a single task; they need no variations. Many others, though, take arguments: one or more filenames, or options to provide variations on their behavior. Once you have more than a single option (or maybe two), you need to parse those arguments in an orderly fashion to be sure that you’ve covered all the possible ways that a user of that script might order those arguments. And come to think of it, even that single task script probably wants -h (or even --help). Let’s take a look at how to parse those arguments and still have a readable, maintainable script.

Your First Argument

If your script just wants a single parameter, you can reference that in your script as $1. You might have statements like echo $1 or cat $1 as part of your script. We don’t recommend using $1 throughout your script as it doesn’t tell the reader anything about this parameter. It’s better, for readability’s sake, if you assign this parameter to a variable with an informative name. If the parameter is meant to be a filename, then choose a variable name like in_file or pathname or similar and assign it right away, early in the script. As we saw in “Default Values”, we can even supply a default value:

filename=${1:-favorite.txt}    # Or maybe use /dev/null as the default?

If the user doesn’t supply any parameter when invoking your script, $1 will be unset. In the preceding example, the shell will assign favorite.txt as the value when parameter one is ...

Get bash Idioms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.