In this example, $1 would refer to cdrom/, and $2 would refer to dir1/.
Another thing that prevented me from writing good scripts was not knowing how to process command-line flags like scriptname -q file1.txt. Thus, if a script I wanted to write was sophisticated enough to need command-line flags, I would use a different language or not write it at all. It turns out
This would be a command that has flags -a and -b. -b is special because it must be followed by an argument such as -b file.txt. It you look at the first line, the getopt command is followed by the letters that can be flags. There is a colon after any letter that requires an additional argument. Later, we see a case statement for each possible argument, with code that either sets a flag or sets a flag and remembers the argument.
What is this $2 business? What's the deal with the —)? What does set - mean? And what about Naomi? Those are all things you can look up later. Just follow the template and it all works.
(OK, if you really want to learn why all of that works, I highly recommend reading the
Here's a larger example that adds a couple additional things. First of all, it uses a function 'usage' to print out the help message. An interesting thing about this function is that the 'echo' lasts multiple lines. Neat, eh? Bash doesn't mind. Second, it makes sure that there are at least MINITEMS items on the command line after the options are processed. Finally, it demonstrates how to process flags that override defaults.
Please steal this code whenever you are turning a simple script into one that takes options and parameters: #!/bin/bash MINITEMS=1 function usage { echo ' Usage: $0 [-d] [-a author] [-c file.txt] [-h] dir1 [dir1 ...] -d debug, don't actual run command -a author name of the author -c copyright override default copyright file -h this help message ' exit 1 } # Set our defaults: DEBUG=false DEBUGCMD= AUTHOR= COPYRIGHT=copyright.txt # Process command-line arguments, possibly overriding defaults args='getopt da:c:h $*' if [ $? != 0 ] then usage fi set -- $args for i do