Iterative and Conditional Syntax

Iterative and conditional statements include the following:

  • for…do…done statements

  • while…do…done statements

  • until…do…done statements

  • select item in itemlist…do…done statements

  • if…elif…else…fi statements

  • case statements

For the syntax of these commands, have a look at the online bash2 documentation (see "To open command documentation").

Here's a bash script that uses interactive user input and an infinite while loop to sum as many integers as the user wants:

#! /bin/bash 
# Interactive user input 
sum=0 
while : 
do
   echo -n "Add another number (y/n):"
   read onward 
   if [ $onward = n ] ; then 
      break 
   fi 
   if [ $onward != y ] ; then 
      echo '"y" or "n" please!'; 
   continue 
   fi 
   echo -n "Enter a number to add to the sum:" 
   read newnum  
   sum=$(($sum + $newnum)) 
   echo "Sum so far is $sum"
done
echo -e "Your sum is $sum"
echo "Bye"

To run the integer sum script:

1.
Save the script in a file named sum.

2.
Give execute permissions to sum:

chmod +x sum

3.
Type sum at the prompt.

4.
Press Enter.

The script will start interactive prompting for numbers (Figure 12.14).

Tip

The colon after while in the command while : provides while with an argument that is always true, meaning that the script will loop forever. This infinite loop is broken in the if statement when the user types n.


Tip

The script does not provide error checking for the user input. If anything besides an integer is entered, the script will end with a syntax error.


Figure 12.14. You can build shell applications by enclosing interactive statements in loops.


Figure 12.15. The Gnome Help Index is a starting point for finding syntax documentation.


Figure 12.16. The Info Pages Table of Contents helps to organize Linux and Gnome documentation.


Figure 12.17. Bash-specific documentation is accessed through the bashz link.


Figure 12.18. Use the links in the bash2 Contents to learn about bash shell programming.


Figure 12.19. You can use the list of reserved shell words to determine the syntax for a particular command.


To open command documentation:

1.
Click the Question Mark icon on the control panel.

The Gnome Help Browser will open to its index page (Figure 12.15).

2.
Click the Info Pages link.

The Info Pages Table of Contents will open (Figure 12.16).

3.
Click the bash2 link to open bash-specific documentation.

The Bash Features page will open (Figure 12.17).

4.
Scroll down the page until you reach the Contents (Figure 12.18).

5.
Click the Reserved Word Index link.

A list of reserved shell words will open (Figure 12.19).

6.
Click the link for a particular command—such as the if command (Figure 12.20)—to determine its syntax.

Figure 12.20. Each command is listed, along with related constructs.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.27