DistributedNetworks DistributedNetworks

Shell Components   «Prev  Next»
Lesson 5Tests
ObjectiveIdentify how and why tests are used in scripts.

Determining which parts of a script to execute

Tests are used within shell scripts to determine which parts of a script to execute and which parts to skip in different situations. For example, a single shell script might include a set of commands for starting a UNIX service and for stopping that service, or commands for backing up all files or backing up only updated files. Different situations may require different combinations of these commands. This is where tests are useful.
To determine which parts of a script to execute, the user sets up a test with the if keyword. One or two blocks of commands are included after the if keyword. If the result of the test is positive (TRUE in computer terms), the first block of commands (noted by the keyword then) is executed. If the result of the test is negative (FALSE in computer terms), the second block of commands (noted by the keyword else) is executed. After these two blocks of commands, other commands can follow that are executed regardless of the test results.
Later in the course, you will learn in detail the different types of tests that are used with an if keyword. These tests include things such as:
  1. Testing the status of files
  2. Using the result of math expressions
  3. Comparing two items
  4. Testing whether a certain variable exists
The following MouseOver applet shows how the if, then, and else keywords are used with blocks of commands. Any command can be included for execution based on the status of the test. For clarity, this example shows how the if/then/else keywords organize the execution of a shell script but it does not include other commands that would be part of a real script. Those will be introduced in a later module.
  1. Executed only if test evaluates to TRUE
  2. Executed only if test evaluates to FALSE.
  3. Executed regardless of the value of test.

Configuring Your Login Script

we will be writing scripts that we will then use in other scripts, so being able to easily call your new scripts is important. You can configure your PATH variable so that your custom scripts are automatically callable, just like any other command, when you start a new command shell. When you open a command shell, the first thing it does is read a login script in your home directory (/Users/<username/> or /home/<username> in OS X or Linux, respectively) and execute any custom commands it finds there. The login script will be .login, .profile, .bashrc, or .bash_profile, depending on your system. To find out which of these files is the login script, add a line like the following to each file:
Test Determines Script
Variables are used in most shell scripts. The next lesson introduces you to them.