The basic principle of if-then statements is that if a certain condition is met, then one thing happens; if the condition is not met, then another thing happens. That is, if you walk into your office in the morning and you see your daily ToDo list, then you sit down and work. If you walk into your office in the morning and you don't see your ToDo list, then you get to lounge all day. Or something like that.
As Figure 10.6 shows, you can create if-then statements using if, then, and else commands. When you set up these conditional statements, the computer then has to test the condition to determine whether it's true or false, and act accordingly. In the next example, we set up a fairly simple if-then conditional statement, requiring the computer to test whether or not a file exists and tell us what it finds. Use the following steps to get started with if-then statements, and see the sidebar called "More on if-then in this section to learn how to expand your if-then statements.
To write an if-then conditional statement:
1. | vi deef To begin, access your editor and the script file. Here we're adapting an existing script (for feedback) in vi. | |
2. | if [ `ls | grep feedback` > /dev/null ] Start the loop with if, then follow it with the conditional statement, in this case if ls | grep feedback. Read this as: "List the files in my home directory and search for a file named feedback. If that file exists (is greater than /dev/null, or more than nothing), then the expression is true." (See the whole script in Figure 10. 6.) Code Listing 10.5. The last line produced by the feedback script differs, depending on the files found.
| |
3. | then echo "There's feedback on the → latest project" On the line immediately after the if statement, enter the command to be carried out or message to be displayed if the if statement is true. In this example, a true if statement would result in "There's feedback on the latest project" being printed onscreen. | |
4. | ||
5. | ||
6. |
Save the script and try it out. In this example, the script will check to see if feedback exists, and print a different message depending on what it finds (Code Listing 10.5). |
More on if-thenUsing the steps provided in this section, try some of these other if-then possibilities:
Type man test for more information about creating conditional statements. |
[ejr@hobbes scripting]$ more status-report #! /bin/sh mail [email protected] -s "Status report for $1" < ~/reports/$1 [ejr@hobbes scripting]$ ./status-report August [ejr@hobbes scripting]$ |
Tip
To see the information provided at the command line, echo it back out with echo $*. The $* variable provides all of the command line input, with $1, $2, and $3 containing the individual items.
Tip
You can also accept input at specified points while a script is running. See the next section for more details.
18.221.222.47