| Lesson 4 | Identifying common errors |
| Objective | Examine errors that involve the if statement. |
Programmers commonly introduce problems into their scripts with incorrect if statements and while loops.
This lesson looks at a few common problems seen with these statements.
Spacing
The shell is very picky about the spacing of these two commands. When typing in your true/false statement,
you must include a space between every piece on the line. You must include all the spaces shown in the if statement and while loop shown below or else you will receive a syntax error.
Basic syntax
Forgetting to include all portions of an
if statement or
while loop will cause a syntax error and can
be difficult to locate in a script. In the script below, the
then statement is missing.
Indenting your code properly will help you spot this problem in your scripts.
if [ "$ answer " = " yes " ]
echo " hello "
fi
Testing numbers
The shell distinguishes between the eq and = operators when testing values in an ifstatement or a while loop. It does the same for ne and != for inequality.
-eq and ne look at values as numbers, = and != look at values as
characters. Using the incorrect operator to test a value is an example of a logic error in your script.
To the eq operator, the values 05, 0005, 5 , and
5 all represent the number 5. The eq operator ignores leading zeros and any spaces in the
value being tested. With the = operator, these would be four different values because they each involve different
characters. eq and ne are flexible in interpreting numbers entered by your user.
The eq and ne operators are great at interpreting numbers, but terrible with characters.
They consider all non-numeric values equal to each other. eq thinks yes equals maybe
and that stop equals go. Run the simulation below to see what happens when you mistakenly use
eq instead of = in a program.
The next lesson examines errors commonly found when collecting and processing user input.