Smarter scripts: Script confusion

  1. Multiple options
  2. Smarter scripts
  3. The current script

What happens if you misspell a switch? Try:

./show --limitt 12 aerosmith songs.txt

What is it doing? Those lines don’t contain “aerosmith”. It’s understandable that the script wouldn’t stop at 12 because we misspelled limit, but what is it showing us? Try:

./show --limitt 12 aerosmith songs.txt | more

and then scroll up a line:

Can't open aerosmith: No such file or directory at ./show line 32.

It isn’t looking for lines containing “aerosmith”. It thinks “aerosmith” is a file that it needs to search through. What is it looking for? All lines that contain the mention of “12”. That’s because the script saw --limitt as a possible switch, and shifted it off the argument list. But it did not see 12 as a possible switch so it left it on. Our script grabs the first item on the argument list as what to search for. In this case, that was 12.

What we need to do is have the script stop when it hits something it doesn’t understand. That’s easy enough to do. Add another switch:

} else {
print "\nI do not understand the option '$switch'.\n\n";

This section must always be the final section of the switch area. If we’re in the switch area it is because the script saw a double-dash. If we get to the final “else”, that is because none of our known switches matched the text following the double-dash. That’s going to be either because the user misspelled it or because the user doesn’t understand what this script does.

So, we have the script tell the user this, call the help subroutine, and exit.

  1. Multiple options
  2. Smarter scripts
  3. The current script