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 to-do list, then you sit down and work. If you walk into your office in the morning and you don’t see your to-do 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 More on If-Then sidebar in this section to learn how to expand your if-then statements.
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 [ -f feedback ] Start the loop with if, and then follow it with a conditional statement, in this case if [ -f feedback ], which checks for the existence of a file named feedback in the current directory. If that file exists, then the expression is true. See the whole script in Figure 10.6. |
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. | else echo "Nope, no feedback yet" On the next line, use else followed by a statement specifying what should happen if the if statement is false. Here, we specify that “Nope, no feedback yet” would be printed onscreen if the feedback file was not found or had nothing in it. |
5. | fi Immediately after the else statement, announce that you’re finished with fi. |
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). |
[ejr@hobbes scripting]$ ./deef Greetings! Say, you're looking mighty sharp today! You were most recently working on scripting/. Nope, no feedback yet [ejr@hobbes scripting]$ touch feedback [ejr@hobbes scripting]$ ./deef Greetings! Say, you're looking mighty sharp today! You were most recently working on scripting/. There's feedback on the latest project [ejr@hobbes scripting]$ |
18.223.32.230