Since loops that count through a range of numbers are often needed,
# Initial value of A is 1
# Keep looping as long as A<=20
# Each time you loop, increment A by 1
for ((A=1; A<=20; A++))
do
echo $A
done
Note that the conditional expression uses normal comparison symbols ( <= ) instead of the alphabetic options ( -le ) used by test .
Don't confuse the C-style for loop with the for...in loop!
4.12.1.5. Making your scripts available to users of other shells
So far we have been assuming that the user is using the
To make your scripts more robust, add a
#!/bin/bash
# script to count from 1 to 20
for ((A=1; A<=20; A++))
do
echo $A
done
I also added a comment line (starting with # ) after the shebang line to describe the function of the script.
The shebang line gets its name from
4.12.1.6. An example
Here is an example of a longer script, taking advantage of some of the scripting features in
#!/bin/bash
#
# number-guessing game
#
# If the user entered an argument on the command
# line, use it as the upper limit of the number
# range.
if [ '$#' -eq 1 ]
then
MAX=$1
else
MAX=100
fi
# Set up other variables
SECRET=$(( (RANDOM % MAX) + 1 )) # Random number 1-100
TRIES=0
GUESS=-1
# Display initial messages
clear
echo 'Number-guessing Game'
echo '--------------------'
echo
echo 'I have a secret number between 1 and $MAX.'
# Loop until the user guesses the right number
while [ '$GUESS' -ne '$SECRET' ]
do
# Prompt the user and get her input
((TRIES++))
echo -n 'Enter guess #$TRIES: '
read GUESS
# Display low/high messages
if [ '$GUESS' -lt '$SECRET' ]
then
echo 'Too low!'
fi
if [ '$GUESS' -gt '$SECRET' ]
then
echo 'Too high!'
fi
done
# Display final messages