Lab #8
CS 2351
UNIX Operating System
Name _________________________________
Section ___________________
This lesson will cover the Korn shell and more of its features. Usage of quotes, relational operators, command substitution and arithmetic functions are shown. Also types of shell control statements such as for in, if-then-elif else, while, and case will be examined. Other uses of date also are mentioned. The script command will also be introduced. |
Change into lab6. What command did you use to do this?_________________________________
Usage of Quotes
The shell is a unique programming language with respect to the way quote signs are used. The shell interprets different characters as "quote characters". These are:
"The double quote mark
The single quote mark
'The backslash character mark
\There are special characters such as %, $, #, &, * and others that lose their special meanings when they have quotes around them. As you may have figured out by now, each of these quote marks have a special and different meaning to the shell. Understanding the differences between them is important.
The Double Quote Mark
Try the following two commands:
print number*
print "number*"
What was the output from the two commands?_____________________________________
________________________________________________________________________
In the first case, the shell substituted the * with the names of all files that start out with number.
In the second case, no substitution occurred. If the shell sees a pair of double quote marks, there will be no substitution between the pair of double quotes.
NOTE: You could have typed in p instead of print above as you made an alias for print in the .kshrc file.
The key behind double quotes is that any character that is otherwise special to the shell loses its special meaning when it appears between a pair of quotes. These special characters are:
*, ?, >, <, >>, and |, blank spaces, tab characters, and newline charactersExceptions to this rule are:
$, `(back quote), and \ (the backslash only if the backslash precedes a $, ", ', newline, or another \; otherwise it loses its special meaning to the shell.)
Type in the following commands:
message="hello there"
print $message
What was printed?______________________________________________________
Next, type in the following:
print "$message"
What was printed?_____________________________________________________
What explanation can you give for the answer you got?
___________________________________________________________________________
The
\ (backslash) is an exception sometimes. Type in the following:print "This is what happens when you \ use the backslash."
What was printed?
___________________________________________________________________________
Type in the following lines. Press the enter key when you get to "the":
print "This is what happens when you \n use the backslash with a newline character."
What was printed?____________________________________________________________
What rule applies here?_________________________________________________________
Next, type in:
print '$message'
What was printed?____________________________________________________________
The Single Quote
As you can see from above, when a shell variable is enclosed in single quote marks, its value is not substituted by the shell. The single quote will remove the special meaning, to the shell, for all the following characters:
*, ?, >, <, >>, and |, blank spaces, tab characters, and newline characters, which are the same for the double quotes, and $, ", `, and \
The shell does not process any characters enclosed within single quotes. Type in the following:
print *
What was the result?___________________________________________________________
Next, type in:
print * '*'
What was the result?
_______________________________________________Next, type in:
var=hello
print $var "$var" '$var'
What was the result? __________________________________________________________
What are the differences between the three outputs?
____________________________ ______________________________________________________________________________________________________________________
In Lab 6, you made a file called ACME2. Its contents are:
print "command $0 has $# arguments"
print "they are $*"
Next, enter
ACME2 August 2345 4897 9856
What were the results? _______________________________________________________
Next use the copy command to copy ACME2 to another file called ACME3. You now have a duplicate of file ACME2.
Next, use the editor to change the double quotes to single quotes in ACME3. Next, type in:
ACME3 August 2345 4897 9856
What was the result? _______________________________________________________
Why or why did it not work?_________________________________________________
_______________________________________________________________________
The Backslash Character
If a special character is preceded by a backslash, it removes the special meaning of only that character to the shell. In other words, the
\ followed by any character removes the special meaning of that character as in the '(single quote).Type in the following:
print \$message
What was the result? _______________________________________________________
Type in (be sure that you do not leave any spaces except the space after the word "print"):
print \<\>\"
print \\
What was the result? _______________________________________________________
The Back Quote
Enclosing a command inside a pair of back quotes causes the command to be executed and its output to be inserted at that precise point on the command line. Remember, the back quote is found on the same key with the tilde (~) on it. Type in the following:
print The date is `date`
What is the result? _______________________________________________________
When the shell processes the command line, it notices the back quote marks. The shell then executes whatever is enclosed between the back quotes--which in this case is the date command. The output from date is then substituted by the shell at that point on the command line and the print command is then executed. As another example, type in the following:
print Your current working directory is `pwd`
What was printed to the screen?_____________________________________________________
Now that you have learned the backquote, you can go back and make some changes in the start file that you wrote in your lab6 directory. You can change it so that the commands date, pwd, and who | wc -l are contained on the same lines as the print statements.
Use the copy command that you made earlier in this lab to copy the start file to newstart. You can also add some comment statements to this file. Make changes in the newstart file so that it looks like the following example:
#!/bin/ksh
# This is a file that will execute several
# commands at the same time.
print Today is `date`
print The directory that I am in is: `pwd`
print "The number of people on the system is: \c"
print `who | wc -l`
This file should already be executable because it was copied from the start file that had execute permission. Just to make sure that it has execute permission, type in:
ls -l newstart
What was the results?__________________________________________________________
You will be using this particular shell script later in another lab assignment. The newstart file that you created above can only be used in the directory in which it was created. Later you will move it to the home directory.
Making short shell scripts to be used in all directories
First of all, return to your home directory by typing in:
cd
Next, make a new directory called bin. Type in:
mkdir bin
Next change to that directory by typing in:
cd bin
You will make three shell scripts in this directory. The first one is one that will allow you to type in a name of a file that you want to find. Use the vi editor to make a file called srch. It should contain the following:
#!/bin/ksh
# This is a program to find a file
# using the Korn Shell
# This returns you to your home directory
cd
# and then prompts for the filename
print "Read in the name of the file\c"
print "that you want to find : \c"
read filename
find . -name $filename
After you have completed this file, make it executable by using the chmod command. When you type in srch, you will be changed to your home directory, and then you will be asked for the name of the file you want to find. You will then get the directory where the file is kept. Do NOT try out this file yet.
Make up another file called prn. This file will allow you to type in the name of the file you want printed out without typing in the lp address every time you type it in. This file assumes that you are always printing out in the same room. Type in the following:
#!/bin/ksh
# This shell script will print a file in
# the Korn shell
print "Type in the name of the file to print out: \c"
read file
lp -dms108pr1 $file
Save this file and make it executable also. This particular prn file will only print out the file in MS 108 on printer number 1. If you print your output somewhere else, you would have to change the destination to something else.
The last file is one that you will use when you want to make a file executable. It will use the chmod command. Name this file chk. Type in the following:
#!/bin/ksh
# Change mode command
# This script will make a file executable
print "Read in name of file \c"
print "to be made executable: \c"
read filename
chmod u+x $filename
print "$filename is now executable: "
ls -l $filename
You will need to make this file executable the same way that you did with the others that you previously created. Later you will be able to use this file instead of typing in the chmod command every time you need to make a file executable.
In order to make these available to you in all of your directories, you will need to go back to your home directory and look at your .profile file. Change to your home directory by typing in:
cd
Use the cat command to look at the file called .profile. This is the initialization file that works when you login to your account. You already added some information to it in an earlier lab. Make sure that these two lines are in the file. If they are not, add them by using the editor to do it.
PATH=$PATH:$HOME/bin
export PATH
Remember, if you make any changes in this file, you usually need to log off the system and then log back on again. However, you also can use the dot command. At the $ prompt, you can type in the following:
$. .profile
You need to type in a . (period), leave a space, and then type in the .profile on the line. The .profile file will become effective immediately.
Change to lab6 again. Next, type in:
srch
When you are asked to name a file, type in:
books
What is the answer that you received?______________________________________________
___________________________________________________________________________
The srch returns to your home directory to do the search so you can look through all of your directories. However, you will still be in the lab6 directory. You should be able to see that in your prompt.
You will use the prn and chk files later.
Command Substitution
You just learned about the use of the backquotes to type in a command on a print line. The backquotes are used in the Bourne shell, the C shell, and the Korn shell. The Korn shell also allows you to place the dollar sign and parentheses $( ) to make a command substitution. Try out these examples:
d=$(date)
print $d
p I am in my $(pwd) directory
p "There are $(who | wc -l)users on the \ system now"
Notice that the last two examples used just the p instead of the word print. You defined an alias for the print command in your .kshrc file. If you did not, you will receive an error message and should use vi to create this alias for print.
Also notice that there is a "\" at the end of the last example. If you run out of space on the first line, you can continue the statement on the second line by using the "\" at the end of the line. There is a second prompt that is used by the Korn shell. It is the ">" by itself. The main prompt returns when you finish the statement.
Relational and Arithmetic Operators in the Korn Shell
Summary of Relational Operators
Operator Description+ addition
- subtraction
* multiplication
/ division
% remainder
& and
&& and (logical)
|| inclusive or (logical)
! not (logical)
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equals
!= not equal to
Arithmetic expressions -Using the ((..)) Command
Arithmetic expressions are made up of constants, variables or any of the arithmetic operators.
The ((..)) command is used for mathematics. There is also a let command but it will not be used here. Some of the newer versions of the Korn shell no longer use the "let" command. All characters between the (( and )) are treated as quoted arithmetic expressions. This is an example:
((X=X+1))
Declaring Integer Variables
As with ordinary variables, integer variables do not need to be declared. A variable can be given an integer value and then used in the arithmetic expression. Try the following example:
X=12
((Y=X * 3))
print $Y
There are no spaces between the variable names and the "=" sign and the value of the variable.
Return to your home directory. Then change to lab4.
For in
There are various shell control structures available in the Korn shell. You will get introduced to a few of them. These will be pointed out to you so you can learn about them.
Make sure that you are still in lab4. Use the dir command to list out the files in this directory. Name three files that are contained in this directory. Be sure you have the telnos files in this lab.
___________________________________________________________________________
The for in loop looks like this in the Korn shell:
For loop-index in argument-list
do
command list
done
This structure assigns the value of the first argument in the argument list to the loop-index and executes the commands between Do and the Done statements. The Do and Done statements mark the beginning and the end of the For loop. In order to see how this structure works, create the following file called name2.
for file in telnos*
do
print "========================================"
print "Sorted contents of $file "
print "========================================"
sort -b +2 $file
done
name2
What was the result?_____________________________________________________________
If-then-else-fi
The if-then-else statements can be used to cause execution of statements to occur if the specified test proves false. The general format of the if-then-else is:
if condition
then
command
command
else
command
command
fi
If the result of the condition is true, then the commands enclosed between the "then" and "else" get executed. Otherwise, the statements between the "else" and "fi" will be executed.
If-then-elif-else-fi
The Elif statement combines the "else" and "if" statements and allows you to construct a nested set of If-then-else structures. The format for this is:
if condition
then
command
command
elif condition
then
command
command
else
command
command
fi
You can use many elifs as you want. At the end of it, you can place an else so that a set of commands can be executed if none of the preceding test expressions are true. To see an example, use the editor to type in the following file called class.
#!/bin/ksh
# This program is written by: (your name goes here)
# This program will allow user to read in the number of
# hours a student has completed. It will then figure out
# what classification a student is.
print "What is your first name"
read first
print "How many hours have you completed?"
read number
if (( $number >= 1 && $number <= 27 ))
then
print "$first, you have $number hours."
print "You are a Freshman."
elif (( $number > 27 && $number <= 60 ))
then
print "$first, you have $number hours."
print "You are a Sophomore."
elif (( $number > 60 && $number <= 89 ))
then
print "$first, you have $number hours."
print "You are a Junior."
else
print "$first, you have $number hours."
print "You are a Senior."
fi
Save this file and make it executable using the chk script created earlier. Now, execute this script by typing in:
class
After you have tried this to see how it works, at the prompt, type in:
r
What happened? __________________________________________________________________
You can then repeat the command several more times. Try out all of the different hours to make sure the entire shell script works.
Script Command
The script command allows you to create a record of several commands by keeping it in a file called typescript. It will store everything that you do, such as typing on your screen and processing a command such as a sort. In order to start a script, you would type in the following:
script
A message comes back saying:
Script started, file is typescript
All of the commands you enter and the output generated will still be echoed to the file typescript. When you type in several pieces of information, you can then quit by pressing the return key and getting to a new line and typing in:
ctrl d
A message comes back saying:
Script done, file is typescript
If you use the ls command, you will find a new file called typescript. You can look at it if you want or you can print out this information in an easier manner.
In order to practice using the script command, at the prompt type in:
script
After you have the message: "Script started, file is typescript," you can try it out using the class program you just made.
First, list out the program itself. What command did you use? _______________________________
Next, try out at least four different numbers to make sure that your program is working. After you have completed this, you can exit from the script command by typing in:
ctrl d
You should then get the message:
Script done, file is typescript
Look at the file "typescript." It should contain both the program and the output to your program. If it does not, back up and execute the last three instructions again. Typescript is strictly a file and not a program.
Next, print out the file typescript. Use the prn shell script that you made earlier in this lab.
*********************************************************
Attach the typescript file to your lab and hand it in with your lab.
*********************************************************
Once you have made this file, if you use the script command again, the new information would overwrite the old version of typescript. If you want to save the contents of typescript, you will need to rename (mv) the file or copy (cp) it to another file. After you have printed out the typescript file, you may remove the file from your lab4 directory. You will be using the script command later in this lab.
While
In the while structure, as long as the test-command returns a true exit status, the structure continues to execute the series of commands delimited by the do and done statements. Before each loop through the commands, the structure executes the test-command. When the exit status of the test-command is false, the structure passes control to the done statement, and the shell continues to the next command. The while structure looks like this:
while test-command
do
commands
done
Type in the following structure called loop.
count=1
while (( count <= 10 ))
do
print $count
(( count=count+1 ))
done
Save this file and make it executable. Try it out. What were the results?
_____________________________________________________________________________
_____________________________________________________________________________
Date options
Earlier in this lab, you were given some different types of date commands. After the date command, you typed in a +% and then a letter of the alphabet such as A or B. The date +%A gave you the full weekday name. The date +%D listed the date in mm/dd/yy form. Try out the following commands and write what the results were when you typed them in:
Date to be typed in: Results:
date ______________________________
date +%B ______________________________
Instructions for the Vi Editor
Instead of typing in all of these from the beginning, use the editing features here. At the prompt, press the escape key. Then press the k key. Use the other keys (h, and l) to get to the right location. You can then delete the character and then use the a or i to make the changes.
Date command: Results:
date +%b _____________________________
date +%d _____________________________
date +%H _____________________________
date +%m _____________________________
date +%M _____________________________
date +%R _____________________________
date +%r _____________________________
There are some other date options. If you cannot figure out what some of these options are, check out the man pages by typing in:
man date
Case
The case structure is similar to an if-then-else type statement. It has a multiple branch decision mechanism. The path that the structure chooses depends on a match between the test string and one of the patterns. The structure is as follows:
case test-string in
pattern-1)
command list1;;
pattern-2)
command list2;;
pattern-3)
command list3;;
pattern-N)
command listN;;
esac
Create the following program called choose.
#!/bin/ksh
# This program was written by: (your name)
# This program will read in the day of week and give a
# message depending on what day of the week it is.
day=$(date +%A)
print "Today is $day"
case "$day" in
Monday)
print "Monday is the Start of week \c"
print " back to work" ;;
Tuesday | Wednesday | Thursday)
print "This is the middle of the week\c"
print " No fun " ;;
Friday)
print "Yea, Friday at last Party time" ;;
Saturday | Sunday)
print "The Weekend is here time to sleep in" ;;
esac
Save this file and make it executable. Run this program and list the output:
_________________________________________________________________________
You have seen how the Korn shell can allow you to customize your account to meet your needs.
Next, you will do some programs in the Bourne shell. You cannot run the Korn shell programs in the Bourne shell. However, if you make Bourne shell programs, they will run in the Korn shell.
You should have the following files now:
bin directory
prn srch chk
lab4 directory
telnos telnos2
telnos3 telnos4 telnos5
tel2 employee
name2 class loop
choose
lab6 directory
start newstart
ACME ACME2 ACME3
combined com com2
copy major
number number2 number3
Please indicate any parts of the lab that were hard to understand.
_________________________________________________________________________
_________________________________________________________________________
05/30/03