O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getopts

Functions, scripts, and other programs are all passed their arguments in the same way — $1 is the first argument to a program, to a script, or to a function. It is difficult for a calling script to tell whether it is calling an external program, script, or function. So it makes sense for a function to act much like a script.

This mkfile script is a wrapper to dd, which provides syntax similar to the mkfile binary in Unix. It uses getopts in the main script to parse its parameters, which shows the basic usage of getopts. Valid options for this script are:

  • -i infile (name of a file to copy input from; the default is /dev/zero)
  • -b blocksize (the size of each block read and written; the default is 512KB)
  • -q for the script to operate quietly
  • -? for usage information

For any other input, the usage information will be displayed. The -i and -b options require a parameter; -q and -? do not. This is all expressed quite succinctly to getopts with the statement 'i:b:q?'. The colon (:) indicates a required parameter, so i: and b: show that -i and -b require a parameter, and it is an error condition if one is not supplied. The other two characters are not followed by a colon so they are standalone flags without parameters. When a parameter is passed, its value is put into the variable OPTARG.

note.ai

Although most shell scripts in this book have a filename extension of .sh, mkfile is an existing ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required