Prac Unix

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Unix/C Shell Programming Prac.

on Mac

INFO230 - UNIX PRACTICAL EXERCISE 1


1.1 INTRODUCTION TO THE WORKSTATION

The workstation environment is one you will be using to do your work. This project unit
is designed to help you to become familiarised with that environment. This includes how
the windowing system works and can be customised, how to use the various unix
commands, the unix C shell environment and an appreciation of the networking
capabilities.

1.2 Exercises

Workstation appearance

When you start up you should also see a help viewer window which introduces and
explains the CDE (Common Desktop Environment). Read through some of the
introductory material there about windows, logging in and out, screen appearance, the
mouse, keyboard etc.

THE CDE has a set of control menus accessed by buttons in the front panel at the bottom
of the screen. Its appearance, in descriptive form, is as follows:

Personal Mailer Style


File Printers
manager apps manager

Calandar Work space Application Help Trash


Netstation Exit manager can
Clock apps

Using the style manager to configure the following according to your own preferences:

1. Select a suitable colour scheme for windows, menus etc.


2. Choose a back-drop.
3. Choose a screen saver.
4. Choose whether you want right- or left-handed mouse operation.

Starting applications

Find and practice starting up the following applications:

1. Netscape
2. The mailer - practice sending yourself or to a friend a mail message
3. Find how to start up the digital clock (you may need to search through a few menus
to do that)
4. Practice creating some new terminal (dterm) windows.
- Practice moving, iconing and closing these windows.

UP.1
Unix/C Shell Programming Prac. on Mac

Moving between workspaces

There are 4 workspaces you can work in. Create a new dterm and practice moving that
window between different workspaces. e.g. Create the window initially in workspace 1,
then move it to workspace 3, then to workspace 4 and then back to workspace 1.

1.3 INTRODUCTION TO UNIX

These exercises are to help you to become familiar with directory and file management.

1.4 Introductory exercises

1. Make a directory in your home directory called “practice”. It will be used to do the
exercises in this project unit. Change directories so this is your current directory.

2. Verify the path by using the “pwd” command.

3. Copy the file /usr1/student/info230/work.tar into this directory. It contains files


and subdirectories in archive format that you will need to do the exercises.

4. Execute the command below to expand the archive you just copied. (the % sign is a
general symbol that is used to refer to the command line prompt and should not be
typed)

% tar xf work.tar

5. Examine the files and directories using the ls command.

6. List the contents of subdirectories using the ls -R command.

7. Change your current directory to “prac1”.

8. Are there any hidden files inside prac1?

9. How large these files?

10. Use the file manager to examine your home directory and the files you just copied
and created.

1.5 Directory creation and deletion

1. Make a directory inside “prac1” called “temp”

2. Create its existence and contents in directory “prac1” using “ls”

3. Now copy the file a.c into “temp”

4. Try to remove the directory using the rmdir command.

5. Enter the “temp” directory, remove the file “a.c” and return to “prac1”

6. Now remove the directory “temp”

UP.2
Unix/C Shell Programming Prac. on Mac

1.6 Filename expansion

Filename expansion is used as a general technique and not just for use with the ls of cp
commands. With ~/practice/prac1 as your current directory examine the operation of the
following commands:

% echo *
% echo *.c
% echo *.*
% echo chapt?
% echo chapt[123]
% echo chapt[123456]
% echo chapt[1-3]
% echo chapt[1-6]
% echo help{a,b,c}.doc1

1.7 wc, cat, more and sort commands

1. Display the contents of the file fruit and veg using the “cat” command.

2. Use the wc command to show how many lines, words and characters are in these
files.

3. “fruit” and “veg” are not sorted. Use the sort command to sort both of these files in
increasing alphabetical order.

4. Combine the “fruit” and “veg” files as follows

% cat fruit veg > produce


(This uses output redirection to redirect the output of the “cat fruit veg” from the
screen to the file “produce”.

5. Display this file using the more command.

% more produce

6. Sort this file in reverse alphabetic order and display it by piping it into more

% sort -r produce | more

7. Display the first 10 lines and then the last 10 lines of produces as follows:

% head produce
% tail produce

8. How would you display the first 15 lines?

UP.3
Unix/C Shell Programming Prac. on Mac

1.8 INTRODUCTION TO SHELL SCRIPTS

Since we have not yet cover vi, use the text editor to create the following scripts in the
directory ~/practice/prac1. The text editor has not been covered in lectures but it is a simple
easy-to-use text editor using a graphical interface.

1.9 Shell variables and echo

Create the following script

story

#!/bin/csh
#
echo ”It was a dark and stormy night”
echo ”Jack and Jill went up the hill”
echo ”Suddenly a shot rang out”
echo ”Jack fell down and broke his crown”
echo ”And Jill came tumbling after”
WARNING: Do not forget to put a CARRIAGE RETURN after the last line of the script.
If you do not, it is incomplete and will be not be interpreted. This applies to all scripts that
you create.

1. Run this script by typing

% chmod u+x story


% story

2. Now run this script by typing

% source story

3. Copy this script into the file story2 and modify it so that Jack and Jill are replaced
by two shell variables $char1 and $char2 contained in the script. Test this script by
typing

% story2

1.10

To examine more of the power of shell scripts, create the following script:

welcome

#!/bin/csh
#
echo ”Hello $user”
echo ”Today is `date`”
echo ”I feel $argv[1]” today
echo ”The following users are logged in: `users`”

UP.4
Unix/C Shell Programming Prac. on Mac

1. Test the script by typing:

% chmod u+x welcome


% welcome good

2. Look up the lecture notes to explain what:

(i) $user does in line 3


(ii) `date` does in line 4
(iii) $argv[1] does in line 5
(iv) `users` does in line 6
3. What will happen if you were to try to execute the script as follows?

% source welcome good

INFO230 - UNIX PRACTICAL EXERCISE 2


For the second week’s exercise, make ~/practice/prac2 your current directory

2.1 Shell variables and lists

This section of the work examines the differences in how words are grouped. Create the
following script:

shellwords

#!/bin/csh
#
set a1 = One two three
set a2 = ”One two three”
set a3 = ’One two three’
set a4 = (One two three)
set a5 = ($a2)
set a6 = $a2 $a3
set a7 = ($a2 $a3)
#
echo $a1 $#a1
echo $a2 $#a2
echo $a3 $#a3
echo $a4 $#a4
echo $a5 $#a5
echo $a6 $#a6
echo $a7 $#a7
echo $a7[2]

1. What does echo $a1 $#a1 do?

UP.5
Unix/C Shell Programming Prac. on Mac

2. Test the script and note the difference in the way quoting and grouping affects the
contents and number of words considered in the shell variables.

3. Which shell variable has the most number of words?

4. Which shell variables have one word and include spaces in the word?

2.2 if-then expression

Create the following script:

checkpattern pattern

#!/bin/csh
#
if ($#argv != 1) then
echo "Usage: checkpattern1 pattern"
exit 1
endif
if ($argv[1] == abc) then
echo "Pattern $argv[1] recognised"
else
echo "Pattern $argv[1] not recognised"
endif

Note: spaces must appear before and after the != and == in the if expression.

This script checks if the command line argument pattern matches an internally stored string
(“abc” in this instance).

1. Test the script using different patterns.

2. Check the argument checking by putting in badly formatted command lines (i.e. 0
or 2 or more command line arguments)

2.3 prepend script

The following script reads input from stdin and places it at the front of a file (prepends it)

prepend filename

#!/bin/csh
# append stdin to a file
# usage: prepend filename
#
set tf = /tmp/ppd.$$
set dest = $argv[1]
cat - $dest > $tf
mv $tf $dest
WARNING: Do not forget to put in a CARRIAGE RETURN after the last line of the
script.

UP.6
Unix/C Shell Programming Prac. on Mac

The directory /tmp is a system directory which all users may access to store temporary
files. /tmp is cleaned out regularly (once a week) so do not leave important files there.

1. What is the shell variable $$?

2. Is the file name $tf created unique? Why would we want create a file name this
way?

3. Create a temporary file called temp1 and type in a few lines of text (it doesn’t matter
what it is). Now type:

% prepend temp1
1111111
2222222
3333333
CTRL-D
% more temp1

The contents of the file temp1 should now have 1111111 etc at the front of the file.
Examine the line in the script

% cat - $dest > $tf

How is this command used to do the prepend operation?

4. Pipes can be used to pass the output of one command to the input of another
command. prepend takes its input from stdin. Instead of the keyboard we can use
a pipe to take the input to prepend from another command e.g. ls. Try this
command

% ls | prepend temp1

Explain how this command works.

2.4 Compressing files and directories

You may find it necessary to reduce the amount of disk space you are using since you are
running out of disk quota. One way to reduce space is to archive and compress files.

1. In the practice/prac2 directory is a directory called “backup”. You see that it


contains several subdirectories and files.

2. Type “%du backup” to see how much space it occupies (roughly).

3. Create an archive of backup and its files and subdirectories by typing

% tar cfv backup.tar backup

UP.7
Unix/C Shell Programming Prac. on Mac

4. Now compress the archive using

% compress backup.tar

The file backup.tar.Z has now been created.

5. Use ls -l to look at how much space it occupies. Compare this with the value from
before.

6. Delete the backup directory and its contents (what is a simple and quick way of
doing this?)

7. Restore the backup directory by first uncompressing it:

% uncompress backup.tar.Z

8. Expand the archive by doing:

% tar xf backup.tar

to restore the backup directory.

tar cfv compress


backup backup.tar backup.tar.Z

tar xfv uncompress


backup backup.tar

2.5 Introduction to vi

The file practice.vi in ~/practice/prac2 contains a tutorial on using vi. The file contains
information on some of the basic commands needed to work with vi and instructions and
exercises to help you to learn how to use them.

Begin the exercise by entering an editing session with vi as follows:

% vi practice.vi

and following the instructions in the file.

If you get confused and you cannot recover, exit from practice.vi using :q! and start again.
If things get really bad, exit using :q! and copy practice.vi.bak and start afresh.

UP.8
Unix/C Shell Programming Prac. on Mac

INFO230 - UNIX PRACTICAL EXERCISE 3


For the third week’s exercise, make ~/practice/prac3 your current directory.

3.1 Subshells

Commands separated by a semi-colon (;) are executed one after the other.
Commands enclosed in parenthesis () are executed in a subshell.
Execute the following two commands.

% ls; date > out1


% (ls; date) > out2

By examining the screen output and the contents of the two files: out1 and out2, explain the
difference between the two commands in terms of unix shell execution.

3.2 Conditional execution

Copy the “fruit” file from ../prac1 into the current directory. Execute the commands:

% grep paper fruit


% grep apple fruit
Which of these commands did not succeed?

The operation || is used to execute the second command if the first wasn’t successful, and
the && is used to execute the second command if the first was successful. Enter the
command and examine the output.

% grep paper fruit || echo “Paper not found”


% grep apple fruit && echo “apple found”
What would happen in the following commands?

% grep paper fruit && echo “Paper not found”


% grep apple fruit || echo “apple found”
3.3 Background execution and job control

Execute the following command

% du / >& /dev/null &


This checks the whole file system and takes a long time, so it should be done in the
background.

1. Look up the du command in the man pages.

2. What does >& do? (N.B. that /dev/null is the null device and all output redirected
there disappears).

UP.9
Unix/C Shell Programming Prac. on Mac

3. The final & means that this command is run as a background process. Examine the
list of background jobs using the “jobs” command after.

4. Now bring that job into the foreground using the “fg” command.

5. Interrupt execution of the job by typing CTRL-Z.

6. Examine the job list again.

7. Now resume background operation using the “bg” command.

8. Finally kill the job using the “kill” command.

3.4 foreach expression

Create the following script which lists the size of all non-zero size files (not directories in
the current directory).

listsize

#!/bin/csh
#
foreach file (*)
if (-f $file && ! -z $file) then
set a = `ls -l $file`
echo $file $a[5]
endif
end
1. Test the script by making it executable and running it.

To help you create files of zero size for testing this script, there is a program called
“makezero” in the directory which will create a file called “zero” of size. You can
create other zero-size files by copying and renaming the file “zero”.

2. Carefully examine the script so that you understand what each line is doing. Test
your understanding with the following questions:

2.1 What does the following line do?

foreach file (*)

2.2 What does the following line do?

if (-f $file && ! -z $file) then

2.3 What does the following line do?

set a = `ls -l $file`

UP.10
Unix/C Shell Programming Prac. on Mac

2.4 What does the following line do? (hint: do an ls -l command on the terminal,
why do we echo $a[5]?)

echo $file $a[5]

3.5 Numeric operations

Create the following script which counts up to a limit which is specified as a command line
argument.

count limit

#!/bin/csh
# Example usage: count 5
#
if ($#argv != 1) then
echo "Usage: count limit"
exit 1
endif

if ($argv[1] <= 0) then


echo "Limit must be positive"
exit 1
endif

set i = 1
while (1)
echo $i
@ i = $i + 1
if ($i > $argv[1]) exit
end
Note: It is important to have a space between the @ and the name of the shell script
variable.

1. Test the script by trying different command lines (correctly formatted and not).

2. Carefully examine the script so that you understand what each line is doing.

3. Modify the script so that it has a second argument so that it counts down from limit
to when it goes below zero in multiple of the second argument.

3.6 Script execution

Scripts can be executed in one of two ways. They can be executed in the current shell
using the source command or you can run them in a subshell by changing their file
permissions and running them directly like any other command in unix. We will examine
the differences here.

Create the following script setalias (using the vi editor if you know how).

UP.11
Unix/C Shell Programming Prac. on Mac

setalias

#!/bin/csh
#
set abc = "One two three"
echo $abc
alias la `ls -a`
alias la
When the source command is used to execute a script, shell variables and aliases
generated by the script do not appear after execution of the script.

When direct execution command is used to execute a script, shell variables and aliases
will be lost because these variables and alises cannot be passed from a subshell process to a
parent process. Make the script executable by doing

% chmod u+x setalias

1. Remove any existing shell variables and alises with the same names as used in the
shell script.

% unset abc
% unalias la
2. Now execute the command

% source setalias
Examine the list of aliases and set variables again. The alias la and abc shell
variables should be present.

3. Remove references to abc and la again by doing:

% unset abc
% unalias la
4. Execute the script as follows:

% setalias
The shell variable abc and alias la should not be present since they could not be
passed back to the parent process.

UP.12
Unix/C Shell Programming Assign. on Mac

INFO230 - UNIX ASSIGNMENT


This assignment is due one week after the completion of the third Unix practical session.

The unix project assignment is marked out of 100.

Make a directory called unix_assign in your home directory and store all your unix
assignment files in that directory.

Question 1 (xstory name1 name2) (10 marks)

Copy the script story2 from the practical exercise 1 to the file xstory and modify it so that
Jack and Jill are replaced by two command line arguments ($argv[1] and $argv[2]). The
script can then be tested as follows:

% xstory Bart Homer

Question 2 (loggedin user) (15 marks)

Create a script called loggedin which checks to see if a particular user is logged in. It has
a single argument and produces one of the two messages, depending on whether the user
indicated is logged in at this moment.

% loggedin s5555555
s5555555 is not logged in

% loggedin s1234567
s1234567 is logged in

Question 3 (sfind filename c) (15 marks)

Create a script called sfind that has two input arguments filename and c. It searches
through the file called filename and prints out in increasing alphabetical order all lines
beginning with the letter given by the argument c.

For example:

% sfind fruit p
passionfruit
peach
plum

Question 4 (quote) (20 marks)

Quoting and the use of escape characters take a bit of practice because of the order in which
the C shell processes a command and the different types of quotes. In this assignment
question you are to create a script called quote which produces the following messages
(use the echo command to produce each line): (n.b. all five (5) lines are to be included
below, also, pay particular attention to the exact characters used; especially note lines 3 and
5 regarding quotes and slashes).

UA.1
Unix/C Shell Programming Assign. on Mac

Alice & Wally’s Cafe


!!^ Welcome ^!!
Hot dog”s $1.50
Coke\~Pepsi $1.30
”*** “`All you can eat`” ***”
Question 5 (listexec suffix) (15 marks)

Modify the listsize script in the practical exercise 3 to create a script called listexec that

(i) uses the while statement instead of the foreach statement

(ii) it lists the size of any files with executable permission whose suffix matches
a particular pattern.

For example:

% listexec uu
a.uu 256
bett.uu 3456
z1.uu 123
Question 6 (fileman) (25 marks)

You are to write a C script, called fileman, that will be used to manage files by allowing
them to be copied, moved or deleted with interactive input from the user. It has the
following three possible command usage formats:

fileman -c filenames
fileman -m filenames
fileman -r filenames
where filenames is a list of one or more file names. The command line options are as
follows:

-c This is used to copy each file in the list of file names specified in the
command line. For each file to be copied the script will prompt the user for
the name of the new file.

-m This is used to rename (move) each file in the list of file names specified in
the command line. For each file the script will prompt the user for the new
name of the file.

-r This is used to remove each file in the list of file names specified in the
command line. The user is prompted for confirmation before a file is
removed.

Write the script so that it will correctly interpret the command line options and arguments to
perform the functions associated with each option. Your script should check for invalid
command lines and, if an error occurs, print out a message showing the correct usage
formats.

UA.2

You might also like