condition
)
action(s)
end
The
condition
must evaluate to a Boolean (true or false). The actions must appear on a
separate line from the word while and the expression. The actions can be combined onto
one line if separated by semicolons, and the end statement can also appear on the same line
as the actions.
foreach
VARIABLE
(
arguments
)
action(s)
end
The
arguments
must be a list or an operation that returns a list. This could include, for
instance,
$@
(or
$argv
) for the list of parameters, the response from a Linux command
such as `ls *.txt`, or an enumerated list such as
(1 3 5 7 9)
. To simulate the counter for
loop, use
‘seq
first step last
‘
to generate the values to iterate over. Neither
first
nor
step
is required and default to 1. For instance,
‘seq 5‘
generates the list
(1 2 3 4
5)
while
‘seq 3 7‘
generates the list
(3 4 5 6 7)
.
7.10.4 Reasons to Avoid csh Scripting
With this brief overview of csh scripting, there are several reasons to not use csh for script-
ing. In spite of the more C-like syntax, the csh scripting is very incomplete and therefore
there are many things that you can easily do in bash scripting that you either cannot do or
cannot do easily in csh. Here we just look at a few.
• There is no facility to write or call functions in csh.
• There is no specific input statement relying instead on the use of
$
<
. The
$
<
operation
obtains input from the standard input used by the script. By default, standard input is the
keyboard. However, when you run the script you can change this to a file, for instance
by running your script as .
/script
<
file
. In this case,
$
<
obtains input from the file,
one line at a time. If you want to obtain just one datum from a file it cannot be done.
You would have to parse the list in
$
<
to break it into individual items. Additionally, you
cannot receive input from both keyboard and file in the same script!
• The substring notation
${string:first:last}
does not exist in csh although the
expr substr
operation is available.
• The one-line if statement in csh does not perform short-circuiting. In bash, the fol-
lowing condition will work correctly whether X has a value or not:
[[ -n $X && $X –gt 0 ]]
but in csh, the equivalent condition
($?X -a $X > 0)
yields an error if X is not defined.
304
◾
Linux with Operating System Concepts
• In many cases, you need to specify statements in multiple lines. This prevents you
from easily issuing such commands either from the command line or in an alias
statement.
• Although the bash scripting language’s syntax has its own peculiarities and oddities,
the need to separate the operators in an arithmetic expression by inserting spaces can
be both annoying and troubling if you forget to do so.
• There are peculiarities with the interpreter leading to errors in some unexpected situ-
ations. One of which deals with quoting and the use of escape characters like \” and \’.
• There are also challenges with respect to properly piping some instructions together
in csh.
*
Neither bash nor csh present the most easily usable scripting languages. If you hope
to develop your own software and run it in Linux, you are better served by learning a
more complete and usable language. Linux has its own interpreters and compilers for perl,
python, php, ruby, and other languages and its own compiler for C/C
++
. If they are not
available in your Linux installation, they are available as open source software and easily
downloaded using yum (see Chapter 13).
7.11 CHAPTER REVIEW
Concepts and terms introduced in this chapter:
• Array—a data structure that can store multiple values. To reference one specific value
you need to specify the index (location) of the value of interest.
• Assignment statement—a programming instruction that assigns a variable a value.
The value can be a literal value, the value stored in another variable, or the result of
some expression such as an arithmetic operation or a Linux command.
• Compound condition—a condition which has multiple parts that are combined
through Boolean operators AND and OR.
• Condition—a comparison that evaluates to true or false. Typically, the comparison is
between a value stored in a variable and either a literal value, a value stored in another
variable, or the result of a computation.
• Counter loop—a loop which iterates a set number of times based on a sequence of
values such as 1 to 10 or 10 to 50 by 2.
*
Tom Christiansen, a Unix developer, has produced a famous document for why you should not use csh for scripting. You
can find a copy posted at http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/.If you are an introductory programmer
or unfamiliar with scripting, you might find many of the code examples to be very cryptic.
Shell Scripting
◾
305
• Else clause—the set of code corresponding with the else statement in a two-way selec-
tion statement. This clause executes if the condition is false.
• Error code—functions can return an integer number that describes the exit status of
the function indicating success or error.
• File condition—a set of conditions that test a file for type or access permission or
other.
• Function—a subroutine; or a set of code that can be invoked from different areas of a
script or program. Functions support modularity.
• Iterator loop—a loop which iterates once per item in a list.
• Local variable—a variable that is accessible only from within a function.
• Loop statement—a programming language instruction which repeats a body of code
based on either a condition, the length of a list, or the sequence of counting values
supplied.
• N-way selection—a selection statement which has n conditions to select between one
of n groups of actions.
• One-way selection—the simplest form of selection statement which tests a condition
and if true, executes the associated action(s).
• Parameter—a value passed to a function that the function might utilize during
execution.
• Script—a small program executed by an interpreter.
• Selection statement—a programming language instruction which evaluates one or
more conditions to select which corresponding action(s) to execute.
• Short circuiting—a technique when evaluating a compound condition such that if the
entire condition can be determined without evaluating the entire statement, it ends.
This occurs when two conditions are ANDed or ORed together. If the first condition
is false, there is no need to evaluate the remaining condition(s) if ANDed together. If
the first condition is true, there is no need to evaluate the remaining condition(s) if
ORed together.
• Subroutine—a piece of stand-alone code that can be invoked from other code. Used
to support modularity. In bash scripting, the unit to implement a subroutine is the
function.
• Substring—a portion of a larger string.
• Then-clause—the set of code corresponding with the then statement in a one-way or
two-way selection statement. This clause executes if the condition is true.
306
◾
Linux with Operating System Concepts
• Two-way selection—a selection statement with one condition that executes one of
two sets of code based on whether the condition is true or false.
• Variable condition—tests available in Linux to determine if a variable is storing a
value or is currently null.
Linux (bash, csh) commands covered in this chapter:
• case—n-way selection statement in bash.
• declare—used to declare a variable and change its attributes in bash.
• echo—output statement in Linux.
• end—used to denote the end of a while loop, foreach loop, or switch statement in csh.
• endif—used to denote the end of an if, if-then, if-then-else, or nested if-then-else
statement in csh.
• elif—used to specify an else if condition in a nested if-then-else statement so that the
statement has more than one possible condition.
• else—used to specify a second option of actions in Linux for the two-way selection
statement.
• exit—used in bash functions to indicate that the function should terminate with a
specified error code. 0 is the default for no error, a positive integer is used to denote
an error.
• expr—a Linux instruction which performs either an arithmetic or string operation.
• for—in bash, the instruction used for either a counter loop or iterator loop.
• foreach—the iterator for loop available in csh.
• fi—in bash, the end of an if-then, if-then-else, or if-then-elif-else statement.
• if—used to begin any selection statement in both bash and csh (excluding the case/
switch).
• length—a string operation to return the number of characters stored in a string.
• let—used in bash scripts to assign a variable the result of an arithmetic computation.
• local—used to declare a variable to be local to a bash function.
• read—the bash input statement. There is no corresponding statement in csh.
• return—used in bash functions to exit a function and return an integer value. In the
case of return, the value can be positive or negative (unlike exit).
Shell Scripting
◾
307
• seq—generate a list of the numeric sequence given the first and last values in the
sequence and a step size. First and step size are optional and default to 1.
• set—used in csh to express an assignment statement.
• switch—the csh version of case, an n-way selection statement.
• then—reserved word in if-then statement to indicate the start of the then-clause.
• unset—used in both bash and csh to remove a value (uninitialized) from a variable.
• until—conditional loop in bash.
• while—conditional loop in bash and csh.
REVIEW QUESTIONS
Assume for all questions that you are using a Bash shell.
For questions 1–8, assume X
=
5, Y
=
10, Z
=
15, and N
=
Frank for each of the prob-
lems. That is, do not carry a value computed in one problem onto another problem.
1. What will
echo $X $Y $Z
output?
2. What will X store after executing
X
=
$Y
+
$Z
?
3. What is wrong with the following statement?
Q
=
$X
4. Does the following result in an error? If not, what value does X obtain?
X
=
$((Y
+
N))
5. Does the following result in an error? If not, what value does X obtain?
let X
=
$N
6. What is the value stored in X after the instruction
((--X))
?
7. What is the value stored in N after the instruction
((N
++
))
?
8. What is the result of the instruction
echo $((Y
++
))
? Would
echo $((
++
Y))
do
something different? NOTE: if you are unfamiliar with C or Java, you will have to
research the difference between the prefix and postfix increment.
9. Which of the following are legal variable names in bash? VARIABLE A_VARIABLE
VARIABLE_1 1_VARIABLE variable A-VARIABLE while WHILE.
For questions 10–14, assume A
=
one and B
=
two.
10. What is output with the statement
echo $A $B
?
11. What is output with the statement
echo "$A $B"
?
12. What is output with the statement
echo '$A $B'
?
13. What is output with the statement
echo $A$B
?
14. What is output with the statement
echo "A B"
?
308
◾
Linux with Operating System Concepts
15. What is the difference in the output of the following two statements?
ls
echo ‘ls‘
16. You have executed the script foo.sh as ./foo.sh 5 10 15 20. What are the values of each
of the following? $0, $1, $2, $3, $4, $5, $#, $*.
For questions 17–22, assume X
=
“Hello World”, Y
=
3, Z
=
5, and S
=
“acegiklnor”.
17. What is output from the statement
echo ‘expr substr "$X" $Y $Z‘
?
18. What is output from the statement
echo ‘expr substr "$X" $Z $Y‘
?
19. What is output from the statement
echo ‘expr substr $S $Y $Z‘
?
20. What is output from the statement
echo ‘expr index "$X" $S‘
?
21. What is output from the statement
echo ‘expr length "$X"‘
?
22. What is output from the statement
echo ‘expr index $S "$X"‘
?
23. Write an echo statement to output on one line the current user’s username, home
directory, and current working directory.
24. Write an echo statement to say “the current date and time are” followed by the result
of the date command.
25. Assume we have variables location and work which store the city name and com-
pany name of the current user. Write an echo statement to output a greeting message
including the user’s username, his/her city name, and the company name.
26. Locate a listing of all ASCII characters. Using the notation \xHH, write an echo state-
ment to output the string “Fun!”
27. What does the following instruction do assuming NAME stores your name?
echo Hello $NAME, how are you today? >> greeting.txt
28. The script below will input two values from the user and sum them. What is wrong
with the script? (there is nothing syntactically wrong). How would you correct it?
#!/bin/bash
read X Y
SUM=$((X+Y))
echo The sum of $X and $Y is $SUM
29. What is the –p option used for in read?
30. Write a script to input five values from the user (keyboard) and output the average of
the five values.
Shell Scripting
◾
309
31. What would you need to do so that the script from #30 would input the data from the
disk file numbers.dat?
32. Write a conditional to test to see if HOURS is greater than or equal to 40.
33. Write a conditional to test to see if the user’s name is not zappaf.
34. What is wrong with the following conditional? There several errors.
[ $X > $Y && $Y > $Z ]
35. Write a conditional statement to test if the variable NUM is between 90 and 100.
36. Write a conditional statement to test to see if the file foo.txt does not exist. The condi-
tion should be true if foo.txt does not exist.
37. Write a condition to determine if the file foo.txt is neither readable nor executable.
38. Write a condition to determine if the file foo.txt is owned by both you the user and
you the group.
39. What is a then-clause?
40. If a person is 21 years or older, they are considered an adult, otherwise they are con-
sidered a child. Write a statement given the variable AGE storing the word adult or
child in the variable STATUS.
41. Write a script which inputs a user’s name and state (location). If the user lives in
either AZ or CA, they are charged a fee of $25. If the user lives in either OH, IN, or
KY, they are charged no fee. Otherwise, they are charged a fee of $10. If their name is
Zappa, Duke, or Keneally, their fee is doubled. Output their name and fee.
42. Assume the program
diskcheck –r
returns the number of bytes remaining
free in the current file system and
diskcheck –a
returns the total capacity of
the file system. You will have to use both of these to obtain the percentage of disk
space remaining to determine what the user should do. NOTE: you cannot just
divide the amount remaining by the total because this will be a fraction less than
zero. Instead, multiply the amount remaining by 100 first, and then divide by the
total to get a percentage remaining. Write a program to determine the amount
remaining and output this percentage and the proper response based on the fol-
lowing table:
Do'stlaringiz bilan baham: |