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. |
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.
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. | |
3. | Click the bash2 link to open bash-specific documentation. The Bash Features page will open (Figure 12.17). |
4. | |
5. | |
6. | Click the link for a particular command—such as the if command (Figure 12.20)—to determine its syntax. |
3.145.202.27