Lab #11
CS 2351
UNIX Operating System
Name _________________________________
Section ___________________
This lab will cover many of the shell control statements used in the C shell. Those control statements covered are: if, goto, if-then-else-endif, if-then-else if-else-endif, foreach, while, and switch. Relational operators and expressions that are used in the C shell are covered. A few error messages you may encounter when you are using the C shell are discussed. The du command, clear, and processes and the kill command are explained. |
Make sure that you are in the C-shell. Your % prompt should be on the screen. Change to the lab4 directory. You will be using some of the files in the directory lab4. The examples in this lab will be of the shell control statements.
Type in:
dir
This was one of the aliases that you typed in your .cshrc file in the last lab. Make sure that the telnos files are in this directory.
Foreach
The foreach command loops through the commands. The first time through the loop, the structure assigns the value of the first argument in the argument-list to the loop-index. When control reaches the End statement, the shell assigns the value of the next argument from the argument-list to the loop-index and executes the commands again. The shell repeats this process until it exhausts the argument-list. The foreach structure looks like the following:
foreach loop-index (argument-list)
commands
end
In order to practice using the foreach structure, type in the following program listed below. Name the file, name4.
# This program is in the C shell
# C shell to demonstrate the foreach loop structure
#
foreach file (telnos*)
echo " ============================="
echo " Sorted Contents of $file "
echo "============================="
sort -b +2 $file
echo
end
NOTE: You must use the # (pound sign) in the first space on the first line of a C shell program. If you do not use the # sign with the C shell statements, you will get an error message. In this example the full path of the shell to execute this script in has been specified.
You must make this file executable. Use the chc file that you made to make this file executable and then run it. What was the result of running this program?
__________________________________________________________________________________
__________________________________________________________________________________
The Bourne shell has a for in control structure that is similar to the foreach structure in the C shell.
Relational Operators used in C shell
Summary of Relational Operators
Operator Meaning == Equal to (compare strings) != Not equal to (compare strings) <= Integer on left is less than or equal to integer on the right >= Integer on left is greater than or equal to integer on the right < Integer on left is less than integer on the right > Integer on left is greater than integer on the right && Logical and - true if expression on the right and left are both true || Logical or - true if expression on the right or left is true
Note that any expression that uses the &, &&, ||, |, <, >, or >> operators must be surrounded by parentheses to prevent the shell from interpreting these characters specially.
If
The format for the if control structure is:
if (expression) simple-command
The if control structure works only with simple commands, not pipes or lists of commands. To see how this command works, type in:
% if (5 > 3) echo five is greater than 3
What was the result? ________________________________________________________________
Goto
The format of a Goto transfers control to the statement beginning with label:. The goto looks like the following:
labelgoto
Where the * represents other code between the goto and the label statements. Type in the following called message for an example of the goto:
# C shell to test goto
if (5 > 3) goto message
echo five is less than three
message:
echo five is greater than three
echo the end
Make message executable by using the chc. What was the message you received? ____________________________________________________
The if and goto statements do not have matches in the Bourne shell or the Korn shell.
If..then..else if then .. else..endif
There are three forms of the if then else control structures. They are as follows:
Example 1
if (expression) then
commands
endif
Example 2
if (expression) then
commands
else
commands
endif
Example 3
if (expression) then
commands
else if (expression) then
commands
else
commands
endif
The first form will execute more complex commands if the expression is true. This form is a one-way branch.
The second form is a two-way branch. If the expression is true, the structure executes the first set of commands. If it is false, the commands between the else and the endif are executed.
The third form performs tests until it finds an expression that is true and then executes the corresponding commands. This is similar to the if then elif else fi structure in the Bourne shell.
An example of the if-then-else if follows. Type in the following program called class3.
# C shell to use the if-then-else if construct
# This program was written by: (Type in your name)
# this program will read in the number of hours a
# student has completed. It will then determine
# what classification the student is
#
echo "Read in number of hours a student has completed:"
set number = $<
if ($number >= 1 && $number <= 27) then
echo Class = 1
else if ($number > 27 && $number <= 60) then
echo Class = 2
else if ($number > 60 && $number <= 89) then
echo Class = 3
else
echo Class = 4
endif
Make this program executable.
Now try out the script command. The script command works in the C shell also like in the Korn shell. When you have the "Script Started, file is typescript," use the cat command to list out the class3 program. Then run class3 several times with different numbers to see how the script works. After you have entered class3 the first time, you can then use the !! to repeat the command. After you have finished, get out of the script command by typing in ctrl-d. Use the prnc shell script to print the typescript file to the printer. Be sure to exit script before trying to print the file.
*********************************************************
Attach this file to your lab and turn it in with your lab.
*********************************************************
While
The while command continues to loop through the commands while the expression is true. If the expression is false the first time it is evaluated, the structure never executes the commands. The format for the while structure is:
while (expression)
commands
end
An example of a while loop follows. Type in the following program called loop3.
# C shell while loop
set count = 1
while ($count <= 10)
echo $count
@ count ++
end
Make loop3 executable. What was the output for this program? ____________________________________________________
__________________________________________________________________________________
Arithmetic Expressions
Notice that the @ was used in this program. These are used to do mathematical calculations in the C shell. In order to assign the result of an expression to a variable, you need to use the built-in @ command. The command is:
@ variable-name operator expression
The variable-name is the name of the variable that you are declaring or assigning a value to. The operator is one of the C assignment operators: =, +=, -=, /=, or %=. The expression is an arithmetic expression that can include most C operators. You can also use the ++ or -- to increment or decrement a variable by one number. Type in the following examples of the use of the @ command. Give the answers to them that you received next to them.
@ a = 2 * 2 echo $a _______________________ @ a = $a + $a echo $a _______________________ @ count = 0 echo $count _______________________ @ count = (5 + 2) echo $count _______________________ @ count +=5 echo $count _______________________ @ count ++ echo $count _______________________
Switch
The Switch structure is similar to the Case structure in the Bourne shell. The shell evaluates the test-string and then compares it to each pattern in turn, from top to bottom. When the first matching pattern is found, its associated list of commands is executed and then the shell skips to the matching endsw. If no match is found and a default condition is supplied, the default list is executed. if no match is found, then execution continues from after the matching endsw. An example of the switch structure is:
switch (test string)
case pattern:
commands
breaksw
case pattern:
commands
breaksw
default:
commands
breaksw
endsw
Type in the following called choose3.
# C shell
# This program was written by: (Type in your name)
#to check different numbers in a Switch structure
#
echo " Enter 1, 2, 3, or 4:"
set number = $<
switch ($number)
case "1":
date
breaksw
case "2":
ls
breaksw
case "3":
pwd
breaksw
case "4":
who | wc -l
breaksw
endsw
After you have completed this program, try it out.
A few Common Errors you may get in the C shell
There are a few errors that students get frequently when they are using the C shell. Unfortunately, some of the messages that you receive do not always help you to find your error.
One error is when you do not put a # (pound sign) in the first line in the first space. If you skip a line or forget to use the # sign, you will get an error similar to this:
<filename>: syntax error at line 5: `newline or ;' unexpected
You need to go back and make sure that you have the # sign in the first line. Hopefully that should correct that error. It is always safer to explicity declare the shell that the script is be executed in by making the first line:
#! /bin/csh
When you are using the "If -then " shell control constructs, you may encounter this error:
if: Empty if.
This means that you probably put the then statement on the next line after the if statement. In the C shell, you must put the "then" on the same line with the if statement. You must also always leave spaces before and after the "=" (equal) sign or any other arithmetic signs in the C shell.
Du Command
There are times when you want to find out how much disk space you have used. The du command displays information on disk usage. It reports how much space is used by a directory (along with all its subdirectories and files) or a file. It displays the number of blocks (512 bytes each) that are occupied by the directory or file.
The Computer Science Department has a limit on how much disk space a student may use on the departmental computer. The maximum limit is set to some number by the Systems Administrators. If you go over that limit, you will first be notified by e-mail that you went over your limit and you will be asked to delete several files. If you do not comply with the systems manager, this information will be sent to the Facilities Committee Chairman. Your account will then be shut off and you will need to visit with the Committee Chairman before you can get your account back. One way to keep track of how much disk space you have used is to use the du command.
If you use du without any option, it displays information only about the working directory and its subdirectories. The last line contains the grand total for the working directory and its subdirectories.
If you are not in your home directory, change back to it. Type in the following:
cd
Check to see that you are back in your home directory. Next type in the following:
du
What was the result? ___________________________________________________________
How many blocks are you using on the system? _______________________________________
Here are two options that you can try. These are:
This option displays information for each file in file-list and for each file in the directories in directory-list. The last line contains the grand total for the working directory.-a all
-s summary This option displays summary information for each of the directories and files you specify. This will give you only one number.
Type in the following:
du -a
What was the result? ____________________________________________________________
____________________________________________________________________________
Next, type in:
du -s
What was the result? ____________________________________________________________
____________________________________________________________________________
The du -a command could also be used if you forgot which directory a file was located in. Du lists each directory and the name of each file in that directory. If you have a long list of directories and files, use the more command to see one screen at a time.
Clearing the screen
While you are entering commands, the print on the terminal screen moves on down towards the bottom of the screen. If you want to clear the screen and start at the top again, you can do that by typing in:
clear
Enter the command:
clear
What happens to the prompt? ________________________________________________________________
Processes
A process is the execution of a command by the UNIX system. The shell that starts up when you log in is a command, or a process. When you give the name of a UNIX command on the command line, a process is initiated. When you run a shell script, another shell process is started, and additional processes are created for each command in the script.
Process Structure
A process structure is hierarchical. It has parents, children and a root. The parent process forks a child process, which in turn can fork other processes. Fork is the name of an operating system routine that creates a new process. One of the first things the UNIX system does to begin execution when a machine is started up is to start a single process--process identification (PID) number 1. This process holds the same position in the process structure as the root directory does in the file structure.
Executing a Command
When you give a shell a command, it usually forks a child process to execute the command. While the child process is executing the command, the parent process sleeps. While a process is sleeping, it does not use computer time. When the child process is completed, it dies. The parent process wakes up and prompts you for another command.
Within a given process, such as your login shell or a subshell, you can declare, initialize, read and change variables. But, by default, a variable is local to a process. When a process forks a child process, the parent does not automatically pass the value of a variable to the child. An example of this was shown earlier in the lab where you used the export command.
Ps Command
A unique process identification number (PID) is assigned at the inception of each process. As long as the process is in existence, it keeps the same PID number.
Next, Issue the command:
ps
What was printed ? _____________________________________________________________
____________________________________________________________________________
Background Processing
One reason for learning about process id numbers is that they can be used with background processing. Although in this class , you do not have any long programs to run, if you take some more computer classes you will write some long programs. These programs will take a long time to run. If you execute the long program, you cannot enter anything else into the computer until after it is completed. The "&" is added to the end of a command and the job is then run in the background. You will receive a process id number for the program and then get the prompt again so you may start working on some other project. An example of how the background processing works follows. Type in the following information that is in bold:
find . -name 'employee' &
After you receive the answer, you may need to press the return key to get the prompt again.
Because these were so short, you get the answer back quickly right after the process id number. If you had a long program it would take more time to get a response. However, the answer could mess up the information that you are entering. You can avoid this by redirecting the output to another file and then you can still work on other things and later look at the other file for the output. An example would be:
find . -name 'employee' > find1 &
[4] 13447
%
If you are using x-windows where you have several windows to work in, you do not need to use the background processing features.
Kill Command
The kill command can be used to terminate a process. The form of the command is
kill <process id>
If you have started to execute a program and realize that there are errors and it will take it a long time to run, you can use the process id number to cancel the job--or kill it. This is another use of the process id number.
At the end of this lab, your directory, lab4 should contain the following files:
| telnos | telnos2 | telnos3 | telnos4 | telnos5 |
| tel | tel2 | message | ||
| employee | sample1 | sample2 | ||
| name2 | name3 | name4 | ||
| class | class2 | class3 | ||
| loop | loop2 | loop3 | ||
| choose | choose2 | choose3 |
Return to the Korn shell, just type in:
chsh
You will be asked for a New shell:
Type in:
/bin/ksh
The next time you log into the system, your default shell will be the Korn shell.
Please indicate any parts of this lab that were hard to understand.
___________________________________________________________________________________
___________________________________________________________________________________
06/04/03