Introduction to Linux-Shell Programming: Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 1
Introduction to Linux-Shell Programming: Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 1
5.2.10.LOOPS
There are three types of loops: while, until and for. The while loop is followed by a
command or an expression enclosed in square brackets, a do keyword, a block of
Trường ĐHSPKT.TP.HCM Thực hành Hệ Điều Hành 9
statements, and terminated with the done keyword. As long as the expression is true, the
body of statements between do and done will be executed.
The until loop is just like the while loop, except the body of the loop will be executed as
long as the expression is false.
The for loop used to iterate through a list of words, processing a word and then shifting it
off, to process the next word. When all words have been shifted from the list, it ends. The
for loop is followed by a variable name, the in keyword, and a list of words then a block of
statements, and terminates with the done keyword. The loop control commands are break
and continue.
EXAMPLE:
while command
do
block of statements
done
------------
while [ expression ]
do
block of statements
done
5.2.11.Break Statement
This command is used to jump out of the loop instantly, without waiting to get the control
command
5.2.12.ARRAYS
(positional parameters) The Bourne shell does support an array, but a word list can be
created by using positional parameters. A list of words follows the built-in set command,
and the words are accessed by position. Up to nine positions are allowed.The built-in shift
command shifts off the first word on the left-hand side of the list. The individual words
are accessed by position values starting at 1.
EXAMPLE
set word1 word2 word3
echo $1 $2 $3
Displays word1, word2, and word3
set apples peaches plums
Shifts off apples
shift
Displays first element of the list
echo $1
Displays second element of the list
echo $2
Displays all elements of the list
echo $*
5.2.13.Command substitution: To assign the output of a UNIX/Linux command to a
variable, or use the output of a command in a string, back quotes are used.
EXAMPLE: variable_name=`command`
echo $variable_name
now=`date`
echo $now
echo "Today is `date`"
5.2.14.FILE TESTING: The Bourne shell uses the test command to evaluate
conditional expressions and has a built-in set of options for testing attributes of