Contact us

Print

Using Control Structures

Table of contents:


Exercise 6


Using Control Structures


Control structures allow your program to make decisions and to make them more compact. They allow us to make decisions based on certain outcomes and they also allow us to check for errors. Some control structures are if, while, until, for and case.

For example we might want to test if the user didn’t type in any number in our little calculator script in “Exercise 4” above. We will re-write the script to catch such errors by using control structures.


1. Make sure you are still in the myscripts directory.
2. Launch your text editor again and type in the following commands.


1. #!/bin/bash
2. #this script will perform a slightly more complex addition using control structures
3. echo "Please type in the first number"
4. read first_num
5. echo "Please type in the second number"
6. read second_num
7. expr $first_num + $second_num > /dev/null 2>&1
8.
9. if $? -eq 0 ; then
10.
11. echo "$first_num plus $second_num equals `expr $first_num + $second_num` ";
12.
13. elif $? –ne 0 ; then
14. echo "You didn’t type in valid numeric values ";
15. fi



The “expr” command returns an exit status below after it has been executed:

Exit status:
0 if the expression is neither null nor 0,
1 if the expression is null or 0,
2 for invalid expressions.

The exit status of any command in Linux is stored in the environmental variable “ $? “

The script is using the above possible values of the exit status of “expr” command as the
“test” for the expression in the square brackets .

Line 9 and line 13 in the above code can be read as:

Line 9: Test if the exit status returned by the expression in line 7 is EQUAL ( -eq) to 0.
If it is then execute line 11
Line 13: Test if the exit status returned by the expression in line 7 is
NOT EQUAL ( -ne) to 0. Then do line 14.

3. Save the code you typed in a file and call it “calc3.sh”

4. Change the permissions on the file you created to make it executable. Type


[root@localhost myscripts]# chmod u+x calc3.sh


5. Run the script by inputting numeric values.


[root@localhost myscripts]# ./ calc3.sh


6. Now run the script using non-numeric values or a mixture of numeric values and
letters.


Created by: system. Last Modification: Monday 24 of November, 2008 18:24:52 EST by wale.

...