Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads