DistributedNetworks DistributedNetworks

Unix Commands  «Prev  Next»
Lesson 6 Identifying common errors
ObjectiveExamine errors involving input from the user.

Identifying Common Errors

Two common user input problems can be solved using the techniques listed below.

Spaces in the input

Description: If your user includes spaces in their input, your command may fail when the input is used in a command.
Example: In the code below, if the user enters a space into his or her value, the if statement will fail. echo "Enter a value: \c" read value if [ $value = "quit" ] then exit else echo "your value was $value" fi
Solution: Put double quotes around user variables. If you surround the $input variable with double quotes in the if statement, it will not fail. The double quotes tell the shell to treat the input as a single value.
echo "Enter an input: \c" read input if [ "
$input" = "quit" ] then exit else echo "your input
was $input" fi

Characters in the input

Description: You want your user to enter a number and they enter an input with characters instead. Any math you try to perform on the value will fail.
Example: The following code creates a variable called total, which equals 10 plus the value entered by the user. This code will fail if your user enters letters instead of numbers. echo "Enter a number: \c" read num total=`expr 10 + $num`
Solution: Check the input for non-numbers before running other commands. Insert the code below to check for this problem. The true/false statement will be true if the user has entered any value other than a number. The –eq operator considers all non-numbers to be equal to each other, but all non-numbers to be not equal to numbers. echo "Enter a number: \c" read num while [ "$num" –eq "non-number" ] then echo "You must enter a number: \c" echo "Enter a number: " read num fi total=`expr 10 + $num`

Click the Exercise link below to practice finding syntax errors in a script.
The next lesson demonstrates the use of echo statements to mark stages of success in a script.