Positional parameters versus flags

We'll start this chapter off with a short recap on positional arguments. As you might remember from Chapter 8, Variables and User Input, we are able to use positional parameters to pass arguments to our scripts.

To put this simply, the following syntax is used:

bash script.sh argument1 argument2 ...

Inside the preceding (fictive) script.sh, we can then grab the values supplied by the user by looking at the positions the arguments are supplied in: $1 is the first argument, $2 is the second, and so on. Remember that $0 is a special argument, which relates to the name of the script: in this case, script.sh.

This approach is relatively simple, but also susceptible to errors. When you write this script, you need to check extensively for the input supplied by the user; did they give enough arguments, but not too many? Or, perhaps some arguments are optional, so a few combinations are possible? All these things need to be considered and, if possible, dealt with.

Besides the script writer (you!), there is also the burden on the script caller. Before they can successfully call your script, they need to be aware of how to pass the needed information. For our scripts, we've applied two practices which are meant to minimize the burden on the user:

  • Our script header contains a Usage: field
  • When our scripts are called incorrectly, we print an error message with a usage hint similar/equal to the header

Still, this approach is error-prone and not always very user-friendly. There is another option though: options, more commonly known as flags.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.151.45