Chapter 3. Controlling How Scripts Run

Once you get beyond some trivial scripts, you'll soon find that a script that just runs command after command after command doesn't work for most real-world scripts. Instead, you need the capability to perform some sort of logic within the program, test conditions, and take alternative measures if certain tests fail. You may need to perform some operation on each file in a directory or back up only selected files. Shell scripting languages offer a variety of ways to test values and then execute different commands based on the results of the tests. All of these things fall under the concept of controlling how your scripts run.

This chapter covers:

  • Advanced variable referencing, useful for conditionals and iteration

  • Iterating with the for and foreach statements

  • Using if-then-else statements to test values and execute different commands based on the results

  • Testing for a variety of values using the switch-case statements

  • Looping while a condition is true

Referencing Variables

Chapter 2 introduced the concepts of variables, named data holders. Each variable can hold a value, which you can later reference by placing a dollar sign in front of the variable name. When it comes to looping and conditional tests, however, you often need more options for referencing variables. This section shows you some of those options.

The Bourne shell, along with bash and ksh, provides another means to reference the value of a variable. The normal means is with a dollar sign: ...

Get Beginning Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.