O'Reilly logo

bash Cookbook, 2nd Edition by JP Vossen, Carl Albing

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

Chapter 13. Parsing and Similar Tasks

This is a chapter of tasks that programmers might recognize. The recipes here aren’t necessarily more advanced than the other bash script recipes in the book, but if you are not a programmer, these tasks might seem obscure or irrelevant to your use of bash. We won’t do much explaining of the reasons why you’d find yourself in these situations (as a programmer, you’ll recognize some if not all of them). Even if you don’t recognize the situations, though, you should read them for what you can learn about bash.

Some of the recipes in this chapter include the parsing of command-line arguments. Recall that the typical way to specify options on a shell script is to have a leading minus sign and a single letter. For example, an option for your script to give fewer messages might use -q as a flag to mean quiet mode. Sometimes an option might take an argument. For example, a user option where you need to specify a username might use -u followed by the username. This distinction will be made clear in this chapter’s first recipe.

Some Linux commands also allow long-form options. Using the previous example of a short-format -u option, a command might also support a long format like --user=username. We will not be showing any long-format options, though they could be used for some of the techniques that we show. The best way to parse long arguments is to use the getopt (note no s) command.

13.1 Parsing Arguments for Your Shell Script

Problem

You want ...

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