You are on page 1of 54

1

Introduction

The first script that we will use will be a simple script that will output the text
Hello Unix. I would suggest using vi to create and edit the file. To create
and edit the file, run the following command:

vi hello.sh
If you dont know how to use vi, I would suggest that you read a quick tutorial
by searching for vi tutorial with the search bar above. To enter input mode
in vi, press i. Now, for the code in this first script, enter the following code in
the file:

#!/bin/sh
# This is my first script.

echo "Hello Unix"


Now save the file and close it by hitting Escape followed by :wq and Return.
The first line of the file tells unix which shell to use to execute the file. /bin/sh
is the default location for the bourne shell. In Linux this will normally point to
the bourne again shell, which is a remake of the original unix shell and works
pretty much the same. The second line of the file is just a simple comment.
Comments are ignored by the shell interpreter but are very useful when
developing large and complex scripts. Everyone forgets what their original
logic or intention was when coding a script and its much easier to read a
comment than it is to try to understand large and complex sections of code.
Before we can run this script, we must first make it executable. To do this we
will use the unix chmod command:

chmod u+x hello.sh


Now our script is executable. This command basically tells unix to set the x
(executable) flag for the user level access of the file. Now we are able to run
the file. If you dont have . in your unix PATH environment variable, then you
will need to proceed the name of the script with ./ to execute it. It is
generally considered to be a security risk to put . in your PATH evironment
variable, so we will assume that you dont have it. Now you can execute your
script by using the following command:

2
./hello.sh
You will see the text Hello Unix output to the console, congratulations, you
have created your first unix script!

Variables

Variables are an important part of any program or script. A variable is a


simple way to refer to a chunk of data in memory that can be modified. A
variable in a unix script can be assigned any type of value, such as a text
string or a number. In unix to create a variable, we simply put in our script:

VARIABLE_NAME=value
Note that we do not have to put the variable name in uppercase, but it is the
standard way of naming variables in unix. The text VARIABLE_NAME can
be anything you want, as long as it only contains numbers, letters and/or an
underscore _. A variable name also cannot start with a number. After the
equal sign you put the value, there must be no space between the variable
name and the equal sign. To use the variable, we simply put a dollar sign $
before the name of the variable in our script code. Lets revise our original
script to use the two words in two variables as such:

#!/bin/sh
# This is my second script.
VAR_1=Hello
VAR_2=Unix

echo "$VAR_1 $VAR_2"


This gives the same output as the original script but uses two variables. This
is not a very exciting use of variable I will admit, lets try something more
interesting. Lets write a program that will open a file and read the head and
tail of it. This can be useful if you want to see the first items in your log and
the last items in your log but you dont want to see the whole log file, which
could be very large. To write this program, we will make use of the unix
commands head and tail. Our script will use a predefined varible called $1.
This variable will display the first item in the list of command line arguments
to your script. You can also access any other command line argument from

3
$1 to $9. You can also use the variable $@ to access all of the command line
arguments in a single variable.

#!/bin/sh
# This program will print the head and tail of a file
# passed in on the command line.

echo "Printing head of $1..."


head $1

echo "" #this prints an extra return...


echo "Printing tail of $1..."
tail $1
Give this program a name of ht.sh (for Head Tail shell script), be sure to give
it execute permission and then run it with the following command:

./ht.sh WEB_LOG
The parameter WEB_LOG must point to an actual text file on your system, it
will open the file and print the head and tail. Now lets assume that we want
the user to be able to input the file name after the script has been run. We
can read input from the console by using the unix read command. Lets
modify the program and try it again:

#!/bin/sh
# This program will read the filename from user input.

echo "Enter the file: "


read FILENAME
echo "Printing head of $FILENAME..."

4
head $FILENAME

echo "" #this prints an extra return...


echo "Printing tail of $FILENAME..."
tail $FILENAME
This way of printing a variable does have limitations, for instance you cannot
print text without a space after the variable name. Suppose that we want to
create a script that will read the head and tail of the file as before, but we
know that the user will always be using files that end with _LOG. If we tried
to open the file $FILENAME_LOG, then it would look for a variable with that
specific name and not a file named $FILENAME + _LOG.

We can fix this by using another way of displaying and using a variable. We
use the format ${VARIABLE_NAME}. Lets modify our program again to
automatically append _LOG to the end of the filename for our users:

#!/bin/sh
# This program will read the filename from user input.

echo "Enter the file: "


read FILENAME
echo "Printing head of ${FILENAME}_LOG..."
head ${FILENAME}_LOG

echo "" #this prints an extra return...


echo "Printing tail of ${FILENAME}_LOG..."
tail ${FILENAME}_LOG
Now if you run the script with the command ./ht.sh WEB it will open the file
WEB_LOG for the user.

5
Unix Lab(doc)

INDEX

S.No

Contents

Page No.

Lab Objective

Introduction About Lab

Guidelines to Students

List of Syllabus Programs

Description about UNIX commands

10

Discription about shells

20

Solutions for Programs

22

Viva Questions and Answers

35

References

55

1.

Demonstrate how to use the following Bourne Shell commands: cat, grep, ls,
more, ps, chmod, finger, ftp, etc.

2.

Use the following Bourne Shell constructs: test, if then, if then else, if then elif,
for, while, until, and case.
Learn tracing mechanisms (for debugging), user variables, BourneShell variables,
read-only variables, positional parameters, reading input to a BourneShell script,
command substitution, comments, and exporting variables. In addition, test on
numeric values, test on file type, and test on character strings are covered.

3.

4.

Copy, move, and delete files and directories

5.

Write moderately complex Shell scripts.

6.

Make a Shell script executable.

7.

Create a ".profile" script to customize the user environment.

8.

Use advanced features of File Transfer Protocol (FTP)

9.

Compile source code into object and executable modules.

10.

Execute programs written in c under UNIX environment

How to Run Shell Scripts


There are two ways you can execute your shell scripts. Once you have created a script
file:
Method 1
Pass the file as an argument to the shell that you want to interpret your script.
Step 1 : create the script using vi, ex or ed
For example, the script file show has the following lines
echo Here is the date and time
date
Step 2 : To run the script, pass the filename as an argument to the sh (shell )
$ sh show
Here is the date and time
Sat jun 03 13:40:15 PST 2006

Method 2:
Make your script executable using the chmod command.
When we create a file, by default it is created with read and write permission turned on
and execute permission turned off. A file can be made executable using chmod.
Step 1 : create the script using vi, ex or ed
For example, the script file show has the following lines
echo Here is the date and time
date
Step 2 : Make the file executable
$ chmod u+x script_file
$ chmod u+x show
Step 3 : To run the script, just type the filename

8
$ show
Here is the date and time
Sat jun 03 13:40:15 PST 2006

How to run C programs


Step 1 : Use an editor, such as vi, ex, or ed to write the program. The name of the file
containing the program should end in .c.
For example, the file show.c contains the following lines :
main()
{
printf( welcome to GNEC );
}
Step 2 : Submit the file to CC ( the C Compiler )
$ cc show.c
If the program is okay, the compiled version is placed in a file called a.out
Step 3 : To run the program, type a.out
$ a.out
Welcome to GNEC

Basic Unix commands


Command
Syntax

CAT
cat [argument] [specific file]

Description
Examples

cat" is short for concatenate. This command is used to


create, view and concatenate files.
cat /etc/passwd
This command displays the "/etc/passwd" file on your screen.
cat /etc/profile
This command displays the "/etc/profile" file on your screen.
Notice that some of the contents of this file may scroll off of
your screen.
cat file1 file2 file3 > file4
This command combines the contents of the first three files
into the fourth file.

Command

pwd

Syntax

pwd

Description
Examples

"pwd" stands for print working directory. It displays


your current position in the UNIX filesystem.
pwd
There are no options (or arguments) with the "pwd"

10
command. It is simply used to report your current working
directory.
Command
Syntax

ls
ls [options] [names]

Description
Examples

"ls" stands for list. It is used to list information about


files and directories.
ls
This is the basic "ls" command, with no options. It provides a
very basic listing of the files in your current working
directory. Filenames beginning with a decimal are considered
hidden files, and they are not shown.
ls -a
The -a option tells the ls command to report information about
all files, including hidden files.
ls -l
The -l option tells the "ls" command to provide a long listing
of information about the files and directories it reports. The
long listing will provide important information about file
permissions, user and group ownership, file size, and creation
date.
ls -al
This command provides a long listing of information about all
files in the current directory. It combines the functionality of
the -a and -l options. This is probably the most used version of
the ls command.
ls -al /usr
This command lists long information about all files in the
"/usr" directory.
ls -alR /usr | more

11

This command lists long information about all files in the


"/usr" directory, and all sub-directories of /usr. The -R option
tells the ls command to provide a recursive listing of all files
and sub-directories.
ls -ld /usr
Rather than list the files contained in the /usr directory, this
command lists information about the /usr directory itself
(without generating a listing of the contents of /usr). This is
very useful when you want to check the permissions of the
directory, and not the files the directory contains.

Command
Syntax
Options

mv
mv [options] sources target
-b backup files that are about to be overwritten or removed
-i interactive mode; if dest exists, you'll be asked whether to
overwrite the file

Description
Examples

The "mv" command is used to move and rename files.


mv Chapter1 Chapter1.bad
This command renames the file "Chapter1" to the new name
"Chapter1.bad".
mv Chapter1 garbage
This command renames the file "Chapter1" to the new name
"garbage". (Notice that if "garbage" is a directory, "Chapter1"
would be moved into that directory).
mv Chapter1 /tmp
This command moves the file "Chapter1" into the directory
named "/tmp".

12

mv tmp tmp.old
Assuming in this case that tmp is a directory, this example
renames the directory tmp to the new name tmp.old.
Command
Syntax
Options

rm
rm [options] files
-d, --directory
unlink FILE, even if it is a non-empty directory
(super-user only)
-f, --force
ignore nonexistent files, never prompt
-i, --interactive
prompt before any removal
-r, -R, --recursive
remove the contents of directories recursively
-v, --verbose
explain what is being done

Description

Examples

The "rm" command is used to remove files and


directories. (Warning - be very careful when removing
files and directories!)
rm Chapter1.bad
This command deletes the file named "Chapter1.bad"
(assuming you have permission to delete this file).
rm Chapter1 Chapter2 Chapter3
This command deletes the files named "Chapter1",
"Chapter2", and "Chapter3".
rm -i Chapter1 Chapter2 Chapter3
This command prompts you before deleting any of the three
files specified. The -i option stands for inquire. You must

13

answer y (for yes) for each file you really want to delete. This
can be a safer way to delete files.
rm *.html
This command deletes all files in the current directory whose
filename ends with the characters ".html".
rm index*
This command deletes all files in the current directory whose
filename begins with the characters "index".
rm -r new-novel
This command deletes the directory named "new-novel". This
directory, and all of its' contents, are erased from the disk,
including any sub-directories and files.

Command
Syntax

cp
cp [options] file1 file2
cp [options] files directory

Options

-b backup files that are about to be overwritten or removed


-i interactive mode; if dest exists, you'll be asked whether to
overwrite the file
-p preserves the original file's ownership, group,
permissions, and timestamp

Description

The "cp" command is used to copy files and directories.


Note that when using the cp command, you must always
specify both the source and destination of the file(s) to be
copied.

Examples

cp .profile .profile.bak

14

This command copies your ".profile" to a file named


".profile.bak".
cp /usr/fred/Chapter1 .
This command copies the file named "Chapter1" in the
"/usr/fred" directory to the current directory. This example
assumes that you have write permission in the current
directory.
cp /usr/fred/Chapter1 /usr/mary
This command copies the "Chapter1" file in "/usr/fred" to the
directory named "/usr/mary". This example assumes that you
have write permission in the "/usr/mary" directory.
Command
Syntax

grep
grep [options] regular expression [files]

Options

-i
-n
-v

case-insensitive search
show the line# along with the matched line
invert match, e.g. find all lines that do NOT

-w

match entire words, rather than substrings

match

Description

Examples

Think of the "grep" command as a "search" command


(most people wish it was named "search"). It is used to
search for text strings within one or more files.
grep 'fred' /etc/passwd
This command searches for all occurrences of the text string
'fred' within the "/etc/passwd" file. It will find and print (on
the screen) all of the lines in this file that contain the text
string 'fred', including lines that contain usernames like "fred"
- and also "alfred".
grep '^fred' /etc/passwd

15

This command searches for all occurrences of the text string


'fred' within the "/etc/passwd" file, but also requires that the
"f" in the name "fred" be in the first column of each record
(that's what the caret character tells grep). Using this moreadvanced search, a user named "alfred" would not be
matched, because the letter "a" will be in the first column.
grep 'joe' *
This command searches for all occurrences of the text string
'joe' within all files of the current directory.

Command
Syntax

mkdir
mkdir [options] directory name

Description
Examples

The "mkdir" command is used to create new directories


(sub-directories).
mkdir tmp
This command creates a new directory named "tmp" in your
current directory. (This example assumes that you have the
proper permissions to create a new sub-directory in your
current working directory.)
mkdir memos letters e-mail
This command creates three new sub-directories (memos,
letters, and e-mail) in the current directory.
mkdir /usr/fred/tmp
This command creates a new directory named "tmp" in the
directory "/usr/fred". "tmp" is now a sub-directory of
"/usr/fred". (This example assumes that you have the proper
permissions to create a new directory in /usr/fred.)
mkdir -p /home/joe/customer/acme
This

command

creates

new

directory

named

16

/home/joe/customer/acme, and creates any intermediate


directories that are needed. If only /home/joe existed to begin
with, then the directory "customer" is created, and the
directory "acme" is created inside of customer.

Command
rmdir
Syntax
rmdir [options] directories
Description

Examples

The "rm" command is used to remove files and


directories. (Warning - be very careful when removing
files and directories!)
rm Chapter1.bad
This command deletes the file named "Chapter1.bad"
(assuming you have permission to delete this file).
rm Chapter1 Chapter2 Chapter3
This command deletes the files named "Chapter1",
"Chapter2", and "Chapter3".
rm -i Chapter1 Chapter2 Chapter3
This command prompts you before deleting any of the three
files specified. The -i option stands for inquire. You must
answer y (for yes) for each file you really want to delete. This
can be a safer way to delete files.
rm *.html
This command deletes all files in the current directory whose
filename ends with the characters ".html".
rm index*
This command deletes all files in the current directory whose
filename begins with the characters "index".
rm -r new-novel

17

This command deletes the directory named "new-novel". This


directory, and all of its' contents, are erased from the disk,
including any sub-directories and files.

Command
Syntax

cd, chdir
cd [name of directory you want to move to]

Description
Examples

"cd" stands for change directory. It is the primary


command for moving around the filesystem.
cd /usr
This command moves you to the "/usr" directory. "/usr"
becomes your current working directory.
cd /usr/fred
Moves you to the "/usr/fred" directory.
cd /u*/f*
Moves you to the "/usr/fred" directory - if this is the only
directory matching this wildcard pattern.
cd
Issuing the "cd" command without any arguments moves you
to your home directory.
cd Using the Korn shell, this command moves you back to your
previous working directory. This is very useful when you're in
the middle of a project, and keep moving back-and-forth
between two directories.

18

Command
Syntax
Description

kill
kill [options] IDs
kill ends one or more process IDs. In order to do this you
must own the process or be designated a privileged user. To
find the process ID of a certain job use ps.

Examples
Command
Syntax

ps
ps [options]

Description

Examples

The "ps" command (process statistics) lets you check


the status of processes that are running on your Unix
system.
ps
The ps command by itself shows minimal information about
the processes you are running. Without any arguments, this
command will not show information about other processes
running on the system.
ps -f
The -f argument tells ps to supply full information about the
processes it displays. In this example, ps displays full
information about the processes you are running.
ps -e
The -e argument tells the ps command to show every process
running on the system.

19

ps -ef
The -e and -f arguments are normally combined like this to
show full information about every process running on the
system. This is probably the most often-used form of the ps
command.
ps -ef | more
Because the output normally scrolls off the screen, the output
of the ps -ef command is often piped into the more command.
The more command lets you view one screenful of
information at a time.
ps -fu fred
This command shows full information about the processes
currently being run by the user named fred (the -u option lets
you specify a username).

Why Use Shells?


Well, most likely because the are a simple way to string together a bunch of UNIX
commands for execution at any time without the need for prior compilation. Also because
its generally fast to get a script going. Not forgetting the ease with which other scripters
can read the code and understand what is happening. Lastly, they are generally
completely portable across the whole UNIX world, as long as they have been written to a
common standard.

20

The Shell History:


The basic shells come in three main language forms. These are (in order of creation) sh,
csh and ksh. Be aware that there are several dialects of these script languages which tend
to make them all slightly platform specific. Where these differences are known to cause
difficulties I have made special notes within the text to highlight this fact. The different
dialects are due, in the main, to the different UNIX flavours in use on some platforms. All
script languages though have at their heart a common core which if used correctly will
guarantee portability.

Bourne Shell:
Historically the sh language was the first to be created and goes under the name of The
Bourne Shell. It has a very compact syntax which makes it obtuse for novice users but
very efficient when used by experts. It also contains some powerful constructs built in.
On UNIX systems, most of the scripts used to start and configure the operating system
are written in the Bourne shell. It has been around for so long that is it virtually bug free.
I have adopted the Bourne shell syntax as the defacto standard within this book.

C Shell:
Next up was The C Shell (csh), so called because of the similar syntactical structures to
the C language. The UNIX man pages contain almost twice as much information for the
C Shell as the pages for the Bourne shell, leading most users to believe that it is twice as
good. This is a shame because there are several compromises within the C Shell which
makes using the language for serious work difficult (check the list of bugs at the end of
the man pages!). True, there are so many functions available within the C Shell that if one
should fail another could be found. The point is do you really want to spend your time
finding all the alternative ways of doing the same thing just to keep yourself out of
trouble. The real reason why the C Shell is so popular is that it is usually selected as the
default login shell for most users. The features that guarantee its continued use in this
arena are aliases, and history lists. There are rumours however, that C Shell is destined to
be phased out, with future UNIX releases only supporting sh and ksh. Differences
between csh and sh syntax will be highlighted where appropriate.

21

Korne Shell:
Lastly we come to The Korne Shell (ksh) made famous by IBM's AIX flavour of UNIX.
The Korne shell can be thought of as a superset of the Bourne shell as it contains the
whole of the Bourne shell world within its own syntax rules. The extensions over and
above the Bourne shell exceed even the level of functionality available within the C Shell
(but without any of the compromises!), making it the obvious language of choice for real
scripters. However, because not all platforms are yet supporting the Korne shell it is not
fully portable as a scripting language at the time of writing. This may change however by
the time this book is published. Korne Shell does contain aliases and history lists aplenty
but C Shell users are often put off by its dissimilar syntax. Persevere, it will pay off
eventually. Any sh syntax element will work in the ksh without change.

22
SOLUTIONS:
WEEK1
Session 1
1.
2.
3.
4.
5.

Log in to the system


Use Vi editor to create a file called myfile.txt which contain
some text.
Correct typing errors during creation
Save the file
Logout of the file

Sol:
$ login: <user name>
$ password: ******
$ vi
~ Unix is Case Sensitive
~ Never leave the Computer without logging out when you are working in a
time sharing or network environments.
Type <Esc>
: wq myfile
$
Session 2
1.
2.
3.
4.
5.
6.
7.

Log into the system


Open the file created in session 1
Add some text
Change some text
delete some text
Save the changes
Logout of the system

Sol:
$ login: <user name>
$ password: ******
$ vi myfile
~ Unix is Case Sensitive
~ Never leave the Computer without logging out when you are working in a
time sharing or network environments.
~ Shell Programming
: wq

23
WEEK2
Log into the system
Use the cat command to create a file containing the following data. Call it
mutable use tabs to separate the fields
1425
4320
6830
1450

ravi
ramu
sita
raju
a.
b.
c.
d.
e.
f.
g.

15.65
26.27
36.15
21.86

use the cat command to display the file, my table


use the vi command to correct any errors in the file, my table
use the sort command to sort the file my table according to the
first field. Call the sorted file my table(same name)
print the file my table
use the cut & paste commands to swap fields 2 and 3 my table.
Call it mytable(same name)
print the new file, my table
logout of the system

Sol:
$ login: <user name>
$ password:******
$ cat c1-14
1425 <tab>
ravi <tab>
4320 <tab>
ramu <tab>
6830 <tab>
sita <tab>
1450 <tab>
raju <tab>
$ cat myfile
$who|more
$ sort +0 -1 mytable

15.65 <tab>
26.27 <tab>
36.15 <tab>
21.86 <tab>

24

WEEK3
a.
b.
c.
d.
e.

f.
g.
h.

log in the system


use the appropriate commands to determine ur login shell
use the /etc/passwd file to verify the result of step b.
use the who command redirect the result to a file called
myfile1.Use the more command to see the contents of myfile1.
Use the date and who commands in sequence ?(in one line) such
that the output of date will display on the screen and the output of
who will be redirected to a file called my file2.Use the more
command to check the contents of myfile2.
write a sed command that deletes the first character in each line in
a file
write a sed command that deletes the character before the last
character in each line in a file.
Write a sed command that swaps the files and second words in
each line in a file

Sol:
$ login: <user name>
$ password:******
$ echo $SHELL
csh
$ who >| myfile1
$ more myfile1
$ date|who >myfile2
$ more myfile2

25
WEEK4
pipe ur /etc/passwd file to awk and print out the home directory of each user.
Develop an interactive grep script that asks for a word and a file name and then
tells how many lines contain that word
Repeat
Part using awk
(d) Sol:
$ awk $2 ==Computers && $3 >10000 {print}Sales.dat
I/P:
1
1
1
2
2
2
2

Clothing
Computers
Textbooks
Clothing
Computers
Supplies
Text books

3141
9161
21312
3252
1232
2242
15462

Computers

1232

O/P:
2

26

WEEK5
a) Write A shell script that takes a command line argument and reports on whether
it is directry ,a file,or something else
b) Write a shell script that accepts one or more file name as a arguments and
converts all of thenm to uppercase,provided they exits in the current directory
c) Write a shell script that determines the period for which a specified user is
working on the system

(a) Sol:
echo "Enter a file name:"
read f
if [ -f $f ]
then
echo "File"
elif [ -d $f ]
then
echo "Directory"
else
echo "Not"
fi

Output:
Directory

27
WEEK6
(a) Write a shell script that accepts a file name starting and ending line numbers
as arguments and displays all the lines between the given line numbers
(b) Write a shell script that deletes all lines containing a specified word I one or
more files supplied as arguments to it.

(a) Sol:
$ awk NR<2 || NR> 4 {print $0} 5 lines.dat
I/P:

line1
line2
line3
line4
line5

O/P:

line1
line5

(b) Sol:
i=1
while [ $i -le $# ]
do
grep -v Unix $i > $i
done

28
WEEK7
a) Write a shell script that computes the gross salary of a employee according to the
following
1) if basic salary is <1500 then HRA 10% of the basic and DA =90% of the basic
2) if basic salary is >1500 then HRA 500 and DA =98% of the basic
The basic salary is entered interactively through the key board
(b)Write a shell script that accepts two integers as its arguments and computes
the value of first number raised to the power of the second number
echo " Enter the Salary "
read sal
if [ $sal<1500] then
da=`expr $sal*90/100`
hra=`expr $sal*10/100`
gsal=expr $sal +$hra+$da
echo $gsal
elif [$sal>1500]
hra=500
da=expr $sal*98/100
gsal=expr $sal+$hra+$da
gross=`expr $sa + $da + $hra`
fi
fi
(b)
a=$1
b=$2
c=pow($a,$b)
echo$c

29

WEEK 8
(a) Write an interactive file handling shell program. Let it offer the user the
choice of copying ,removing ,renaming or linking files. Once the use has made a
choice, have the program ask the user for necessary information, such as the file
name ,new name and so on.
(b) Write a shell script that takes a login name as command line argument and
reports when that person logs in
(c) Write a shell script which receives two files names as arguments. It should
check whether the two file contents are same or not. If they are same then second
file should be deleted.

PROGRAM
echo "Enter I File Name:"
read f1
echo "Enter II File Name:"
read f2
d=`cmp $f1 $f2`
d1=""
if [ $d -eq $d2 ]
then
echo "Two Files are similar and $f2 is deleted"
rm $f2
else
echo "Two Files differ each other"
fi

30
WEEK 9
(a) Write a shell script that displays a list of all files in the current directory to
which the user has read write and execute permissions
(b) Develop an interactive script that asks for a word and file name and then
tells how many times that word occurred in the file.
(c) Write a shell script to perform the following string operations.
1) To extract a sub string from a given string
2) To find the length of a given string
(a) PROGRAM
# File Name : list.sh
#!/bin/bash
read -p "Enter a directory name : " dn
if [ -d $dn ]; then
printf "\nFiles in the directory $dn are :\n"
for fn in `ls $dn`
do
if [ -d $dn/$fn ]; then
printf "<$fn> Directory "
elif [ -f $dn/$fn ]
then
printf "$fn File "
fi
if [ -r $dn/$fn ]; then
printf " Read"
fi
if [ -w $dn/$fn ];then
printf " Write"
fi
if [ -x $dn/$fn ];then
printf " Execute"
fi
printf "\n"
done
else
printf "\n$dn not exists or not a directory"
fi

31

(b) PROGRAM
# File Name : wcount.sh
#!/bin/bash
read -p "Enter a file name : " fn
if test -f $fn
then
echo "The contents of the file $fn is :"
cat $fn
echo "No. of Line
: `wc -l $fn`"
echo "No. of Words
: `wc -w $fn`"
echo "No. of Characters: `wc -c $fn`"
else
echo "$fn is not exists or not a file"
fi
(c) PROGRAM
Print Enter the String:\c
read strIn
strlen=${# strIn}
print the string length is : $strlen
$ strlen.scr
O/P:
Enter the String: Now is the time
The String length : 15

32

WEEK 10
Write a C program that takes one or more file or directory names as command line
input and reports the following information on the file.
1.
2.
3.
4.

file type
number of links
read, write and execute permissions
time of last access

(Note: use /fstat system calls)


PROGRAM
#include<stdio.h>
main()
{
FILE *stream;
int buffer_character;
stream=fopen(test,r);
if(stream==(FILE*)0)
{
fprintf(stderr,Error opening file(printed to standard error)\n);
fclose(stream);
exit(1);
}
}
if(fclose(stream))==EOF)
{
fprintf(stderr,Error closing stream.(printed to standard error)\n);
exit(1);
}
return();
}

33

WEEK 11
Write C program that simulate the following unix commands
(a) mv
(b) cp
/* File Name : bspace1.c */
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp;
char ch;
int sc=0;
fp=fopen(argv[1],"r");
if(fp==NULL)
printf("unable to open a file",argv[1]);
else
{
while(!feof(fp))
{
ch=fgetc(fp);
if(ch==' ')
sc++;
}
printf("no of spaces %d",sc);
printf("\n");
fclose(fp);
}
}

34

WEEK 12
Write a c program that simulates ls command
(Use system calls /directory API)
PROGRAM:
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
int fd,i;
char ch[1];
if (argc<2)
{ printf("Usage: mycat filename\n");
exit(0);
}
fd=open(argv[1],O_RDONLY);
if(fd==-1)
printf("%s is not exist",argv[1]);
else
{
printf("Contents of the file %s is : \n",argv[1]);
while(read(fd,ch,1)>0)
printf("%c",ch[0]);
close(fd);
}

35

Viva Questions & Answers


What is a Make file?
Make file is a utility in Unix to help compile large programs. It helps by only compiling
the portion of the program that has been changed

Could you tell something about the Unix System Kernel?


The kernel is the heart of the UNIX operating system, its
responsible for controlling the computers resources and
scheduling user jobs so that each one gets its fair share of
resources.

How can you tell what shell you are running on UNIX
system?
You can do the Echo $RANDOM. It will return a undefined
variable if you are from the C-Shell, just a return prompt if you
are from the Bourne shell, and a 5 digit random numbers if you
are from the Korn shell. You could also do a ps -l and look for
the shell with []

What do you mean by u-area (user area) or u-block?


This contains the private data that is manipulated only by the
Kernel. This is local to the Process, i.e. each process is
allocated a u-area.

What scheme does the Kernel in Unix System V follow while


choosing a swap device among the multiple swap devices?
Kernel follows Round Robin scheme choosing a swap device
among the multiple swap devices in Unix System V.

List the system calls used for process management:


System calls
fork()
exec()
wait() []

Description
To create a new process
To execute a new program in a process

36

How do you change File Access Permissions?


Every file has following attributes:
owners user ID ( 16 bit integer )
owners group ID ( 16 bit integer )
File access mode word
r w x -r w x- r w x
(user permission-group permission-others permission)
r-read, w-write, x-execute
To change the access mode, we use chmod(filename,mode).
Example:
To change mode of myfile to rw-rw-r (ie. read, write
permission for user - []

Explain the layered aspect of a UNIX system. What are the


layers? What does it mean to say they are layers?
A UNIX system has essentially three main layers:
. The hardware
. The operating system kernel
. The user-level programs
The kernel hides the systems hardware underneath an
abstract, high-level programming interface. It is responsible for
implementing many of the facilities that users and user-level
programs take for granted.
The kernel assembles all of the following UNIX concepts from
lower-level []

What is the use of grep command?


grep is a pattern search command. It searches for the pattern,
specified in the command line with appropriate option, in a
file(s).
Syntax : grep Example : grep 99mx mcafile

What difference between cmp and diff commands?


cmp - Compares two files byte by byte and displays the first
mismatch
diff - tells the changes to be made to make the files identical

What is the significance of the tee command?

37
It reads the standard input and sends it to the standard output
while redirecting a copy of what it has read to the file specified
by the user.

Is du a command? If so, what is its use?


Yes, it stands for disk usage. With the help of this command
you can find the disk capacity and free space of the disk.

How to terminate a process which is running and the


specialty on command kill 0?
With the help of kill command we can terminate the process.
Syntax: kill pid Kill 0 - kills all processes in your system except
the login shell.

38

Explain kill() and its possible return values.


There are four possible results from this call:
kill() returns 0. This implies that a process exists with the given
PID, and the system would allow you to send signals to it. It is
system-dependent whether the process could be a zombie.
kill() returns -1, errno == ESRCH either no process exists with
the given PID, or []

What does the command $who | sort logfile > newfile


do?
The input from a pipe can be combined with the input from a
file . The trick is to use the special symbol - (a hyphen) for
those commands that recognize the hyphen as std input.
In the above command the output from who becomes the std
input to sort , meanwhile sort opens the file []

What are shell variables?


Shell variables are special variables, a name-value pair created
and maintained by the shell.
Example: PATH, HOME, MAIL and TERM

How many prompts are available in a UNIX system?


Two prompts, PS1 (Primary Prompt), PS2 (Secondary Prompt).

Is it possible to create new a file system in UNIX?


Use su command. The system asks for password and when
valid entry is made the user gains super user (admin) privileges.

How the Kernel handles the copy on write bit of a page,


when the bit is set?
In situations like, where the copy on write bit of a page is set
and that page is shared by more than one process, the Kernel
allocates new page and copies the content to the new page and
the other processes retain their references to the old page. After
copying the Kernel updates the page []

Difference between the fork() and vfork() system call?

39
During the fork() system call the Kernel makes a copy of the parent processs address
space and attaches it to the child process.But the vfork() system call do not makes any
copy of the parents address space, so it is faster than the fork() system call. The child
process as a result of the vfork() []

How the Kernel handles the fork() system call in traditional


Unix and in the System V Unix, while swapping?
Kernel in traditional Unix, makes the duplicate copy of the
parents address space and attaches it to the childs process,
while swapping. Kernel in System V Unix, manipulates the
region tables, page table, and pfdata table entries, by
incrementing the reference count of the region table of shared
regions.

What are the requirements for a swapper to work?


The swapper works on the highest scheduling priority. Firstly it
will look for any sleeping process, if not found then it will look for
the ready-to-run process for swapping. But the major
requirement for the swapper to work the ready-to-run process
must be core-resident for at least 2 seconds before swapping
out. And for swapping []

What is Expansion swap?


At the time when any process requires more memory than it is
currently allocated, the Kernel performs Expansion swap. To do
this Kernel reserves enough space in the swap device. Then the
address translation mapping is adjusted for the new virtual
address space but the physical memory is not allocated. At last
Kernel swaps the []

What is Fork swap?


fork() is a system call to create a child process. When the parent
process calls fork() system call, the child process is created and
if there is short of memory then the child process is sent to the
read-to-run state in the swap device, and return to the user state
without swapping the parent process. []

What are the entities that are swapped out of the main
memory while swapping the process out of the main
memory?

40
All memory space occupied by the process, processs u-area,
and Kernel stack are swapped out, theoretically.
Practically, if the processs u-area contains the Address
Translation Tables for the process then Kernel implementations
do not swap the u-area.

Is the Process before and after the swap are the same? Give
reason.
Process before swapping is residing in the primary memory in
its original form. The regions (text, data and stack) may not be
occupied fully by the process, there may be few empty slots in
any of the regions and while swapping Kernel do not bother
about the empty slots while swapping the process outAfter
swapping []

What are the events done by the Kernel after a process is


being swapped out from the main memory?
When Kernel swaps the process out of the primary memory, it
performs the following:
Kernel decrements the Reference Count of each region of the
process. If the reference count becomes zero, swaps the region
out of the main memory.
Kernel allocates the space for the swapping process in the swap
device.
Kernel locks the other swapping process while []

What is major difference between the Historic Unix and the


new BSD release of Unix System V in terms of Memory
Management?
Historic Unix uses Swapping entire process is transferred to
the main memory from the swap device, whereas the Unix
System V uses Demand Paging only the part of the process is
moved to the main memory. Historic Unix uses one Swap
Device and Unix System V allow multiple Swap Devices

What is an advantage of executing a process in


background?
The most common reason to put a process in the background is
to allow you to do something else interactively without waiting
for the process to complete. At the end of the command you add
the special background symbol, &. This symbol tells your shell

41
to execute the given command in the background.
Example: cp *.* []

What Happens when you execute a program?


When you execute a program on your UNIX system, the system
creates a special environment for that program. This
environment contains everything needed for the system to run
the program as if no other program were running on the system.
Each process has process context, which is everything that is
unique about the state of []

What are the process states in Unix?


As a process executes it changes state according to its
circumstances. Unix processes have the following states:
Running : The process is either running or it is ready to run .
Waiting : The process is waiting for an event or for a resource.
Stopped : The process has been stopped, usually by receiving a
signal.
Zombie : The []

42

What is a zombie?
When a program forks and the child finishes before the parent,
the kernel still keeps some of its information about the child in
case the parent might need it - for example, the parent may
need to check the childs exit status. To be able to get this
information, the parent calls `wait(); In the []

How can a parent and child process communicate?


A parent and child can communicate through any of the normal
inter-process communication schemes (pipes, sockets,
message queues, shared memory), but also have some special
ways to communicate that take advantage of their relationship
as a parent and child. One of the most obvious is that the parent
can get the exit status of the []

How can you get/set an environment variable from a


program?
Getting the value of an environment variable is done by using
`getenv().
Setting the value of an environment variable is done by using
`putenv().

Explain fork() system call.


The `fork() used to create a new process from an existing
process. The new process is called the child process, and the
existing process is called the parent. We can tell which is which
by checking the return value from `fork(). The parent gets the
childs pid returned to him, but []

What are various IDs associated with a process?


Unix identifies each process with a unique integer called
ProcessID. The process that executes the request for creation
of a process is called the parent process whose PID is Parent
Process ID. Every process is associated with a particular user
called the owner who has privileges over the process. The
identification for the user is []

Brief about the initial process sequence while the system


boots up.

43
While booting, special process called the swapper or
scheduler is created with Process-ID 0. The swapper manages
memory allocation for processes and influences CPU allocation.
The swapper inturn creates 3 children:
the process dispatcher,vhand and dbflush with IDs 1,2 and 3
respectively.
This is done by executing the file /etc/init. Process dispatcher
gives birth to the shell. []

44

What is a shell?
A shell is an interactive user interface to an operating system
services that allows an user to enter commands as character
strings or through a graphical user interface.
The shell converts them to system calls to the OS or forks off a
process to execute the command. System call results and other
information from the OS []

How does the inode map to data block of a file?


Inode has 13 block addresses. The first 10 are direct block
addresses of the first 10 data blocks in the file. The 11th
address points to a one-level index block. The 12th address
points to a two-level (double in-direction) index block. The 13th
address points to a three-level(triple in-direction)index block.
This provides a very large maximum []

Discuss the mount and unmount system calls


The privileged mount system call is used to attach a file system
to a directory of another file system; the unmount system call
detaches a file system. When you mount another file system on
to your directory, you are essentially splicing one directory tree
onto a branch in another directory tree. The first argument to
[]

How do you create special files like named pipes and device
files?
The system call mknod creates special files in the following
sequence.
1. kernel assigns new inode,
2. sets the file type to indicate that the file is a pipe, directory or
special file,
3. If it is a device file, it makes the other entries like major, minor
device numbers.
For example: If the device is a disk, major []

What are links and symbolic links in UNIX file system?


A link is a second name (not a file) for a file. Links can be used
to assign more than one name to a file, but cannot be used to
assign a directory more than one name or link filenames on
different computers.

45
Symbolic link is a file that only contains the name of another
file.Operation []

What are the Unix system calls for I/O?


open(pathname,flag,mode) - open file
creat(pathname,mode) - create file
close(filedes) - close an open file
read(filedes,buffer,bytes) - read data from an open file
write(filedes,buffer,bytes) - write data to an open file
lseek(filedes,offset,from) - position an open file
dup(filedes) - duplicate an existing file descriptor
dup2(oldfd,newfd) - duplicate to a desired file descriptor
fcntl(filedes,cmd,arg) - change properties of an open file
ioctl(filedes,request,arg) - change the behaviour []

What Happens when you execute a program?


When you execute a program on your UNIX system, the
system creates a special environment for that program. This
environment contains everything needed for the system to run
the program as if no other program were running on the system.
Each process has process context, which is everything that is
unique about the state of []

What are the process states in Unix?


As a process executes it changes state according to its
circumstances. Unix processes have the following states:
Running : The process is either running or it is ready to run .
Waiting : The process is waiting for an event or for a resource.
Stopped : The process has been stopped, usually by receiving a
signal.
Zombie : The []

What is a zombie?
When a program forks and the child finishes before the parent,
the kernel still keeps some of its information about the child in
case the parent might need it - for example, the parent may
need to check the childs exit status. To be able to get this
information, the parent calls `wait(); In the []

How can a parent and child process communicate?

46
A parent and child can communicate through any of the normal
inter-process communication schemes (pipes, sockets,
message queues, shared memory), but also have some special
ways to communicate that take advantage of their relationship
as a parent and child. One of the most obvious is that the parent
can get the exit status of the []

How can you get/set an environment variable from a


program?
Getting the value of an environment variable is done by
using `getenv().
Setting the value of an environment variable is done by using
`putenv().

Explain fork() system call.


The `fork() used to create a new process from an existing
process. The new process is called the child process, and the
existing process is called the parent. We can tell which is which
by checking the return value from `fork(). The parent gets the
childs pid returned to him, but []

What are various IDs associated with a process?


Unix identifies each process with a unique integer called
ProcessID. The process that executes the request for creation
of a process is called the parent process whose PID is Parent
Process ID. Every process is associated with a particular user
called the owner who has privileges over the process. The
identification for the user is []

Brief about the initial process sequence while the system


boots up.
While booting, special process called the swapper or
scheduler is created with Process-ID 0. The swapper manages
memory allocation for processes and influences CPU allocation.
The swapper inturn creates 3 children:
the process dispatcher,vhand and dbflush with IDs 1,2 and 3
respectively.
This is done by executing the file /etc/init. Process dispatcher
gives birth to the shell. []

What is a shell?

47
A shell is an interactive user interface to an operating
system services that allows an user to enter commands as
character strings or through a graphical user interface.
The shell converts them to system calls to the OS or forks off a
process to execute the command. System call results and other
information from the OS []

How does the inode map to data block of a file?


Inode has 13 block addresses. The first 10 are direct block
addresses of the first 10 data blocks in the file. The 11th
address points to a one-level index block. The 12th address
points to a two-level (double in-direction) index block. The 13th
address points to a three-level(triple in-direction)index block.
This provides a very large maximum []

Discuss the mount and unmount system calls


The privileged mount system call is used to attach a file
system to a directory of another file system; the unmount
system call detaches a file system. When you mount another file
system on to your directory, you are essentially splicing one
directory tree onto a branch in another directory tree. The first
argument to []

How do you create special files like named pipes and device
files?
The system call mknod creates special files in the following
sequence.
1. kernel assigns new inode,
2. sets the file type to indicate that the file is a pipe, directory
or special file,
3. If it is a device file, it makes the other entries like major, minor
device numbers.
For example: If the device is a disk, major []

What is a FIFO?
FIFO are otherwise called as named pipes. FIFO (first-in-firstout) is a special file which is said to be data transient. Once data
is read from named pipe, it cannot be read again.
Also, data can be read only in the order written. It is used in
interprocess communication where a process writes to one end
of []

48

What are links and symbolic links in UNIX file system?


A link is a second name (not a file) for a file. Links can be used
to assign more than one name to a file, but cannot be used to
assign a directory more than one name or link filenames on
different computers.
Symbolic link is a file that only contains the name of another
file.Operation []

What are the Unix system calls for I/O?


open(pathname,flag,mode) - open file
creat(pathname,mode) - create file
close(filedes) - close an open file
read(filedes,buffer,bytes) - read data from an open file
write(filedes,buffer,bytes) - write data to an open file
lseek(filedes,offset,from) - position an open file
dup(filedes) - duplicate an existing file descriptor
dup2(oldfd,newfd) - duplicate to a desired file descriptor
fcntl(filedes,cmd,arg) - change properties of an open file
ioctl(filedes,request,arg) - change the behaviour []

Brief about the directory representation in UNIX


s a file containing a correspondence between filenames and
inodes. A directory is a special file that the kernel maintains.
Only kernel modifies directories, but processes can read
directories. The contents of a directory are a list of filename and
inode number pairs. When new directories are created, kernel
makes two entries []

What is inode?
All UNIX files have its description stored in a structure called
inode. The inode contains info about the file-size, its location,
time of last access, time of last modification, permission and so
on. Directories are also represented as files and have an
associated inode. In addition to descriptions about the file, the
inode contains pointers []

49

How are devices represented in UNIX?


All devices are represented by files called special files that are
located in/dev directory. Thus, device files and other files are
named and accessed in the same way. A regular file is just an
ordinary data file in the disk. A block special file represents a
device with characteristics similar to a disk (data transfer []

Brief about the directory representation in UNIX


A Unix directory is a file containing a correspondence between
filenames and inodes. A directory is a special file that the kernel
maintains. Only kernel modifies directories, but processes can
read directories. The contents of a directory are a list of filename
and inode number pairs. When new directories are created,
kernel makes two entries []

What is inode?
All UNIX files have its description stored in a structure called
inode. The inode contains info about the file-size, its location,
time of last access, time of last modification, permission and so
on. Directories are also represented as files and have an
associated inode. In addition to descriptions about the file, the
inode contains pointers []

How are devices represented in UNIX?


All devices are represented by files called special files that are
located in/dev directory. Thus, device files and other files are
named and accessed in the same way. A regular file is just an
ordinary data file in the disk. A block special file represents a
device with characteristics similar to a disk (data transfer []
How is the command
$cat file2 different
from $cat >file2
Answer

The Commond $cat file in unix is used to display the content


of the file and where as commond $cat >> file is to append
the text to the end of the file without overwritting the
information of the file. Incase if the file does not exist in the
directory the commond will create a newfile in file system.

50

$cat >file means to create a new file $cat file means to open
an existing file.
Answered By: selva,ravi

Date: 7/13/2007

cat > file it means creating file for file cat file it means used
to display the file content

Explain the steps that


a shell follows while
processing a
command.

Answer

When processing a command the searchs for the utility for


the command in the directories specified in the PATH varible
and it in invokes that utility. That utility will execute the
command with help of kernel and the output is given to shell.
And then the displays out put to the user.

Explain the steps that


a shell follows while
processing a
command.

Answer

When processing a command the searchs for the utility for


the command in the directories specified in the PATH varible
and it in invokes that utility. That utility will execute the
command with help of kernel and the output is given to shell.
And then the displays out put to the user.

Which command is
used to delete all files
in the current
directory and all its
sub-directories?

Answer

#rm -fr <Directory name>


# rm -rf *
Answered By: Amit Shiknis

Date: 12/25/2007

51

rm -r *

What is the use of the


command "ls -x
chapter[1-5]"

Answer

Yes you are correct. It stands for listing the files Chapter with
suffix 1 to 5 but it will display the files in columns as with-x
option.

How does the kernel


differentiate device
files and ordinary
files?

Device filles are of 2 types --- charcater device file and block
device file
type field in the file's inode structure
Answer

b--- block device file


c--- character device file

How to switch to a
super user status to
gain privileges?

Answer

Use su command. The system asks for password and when


valid entry is made the user gains super user (admin)
privileges.

What are shell


variables?

Answer

Shell variables are system environment variables.They


include
TERM,SHELL, MAIL

52

the output of the shell variable we can see by typing the


command
$>echo $TERM
ansi
at the prompt.

What is redirection?

Redirection is a feature in Unix where the data from the


standard out put or a file,so on.can be redirected i.e divert to
a file or a program and vice versa.
Answer

> -- out put redirection


>> -- out put redirectin(appending at the last)
< -- input redirection

How to terminate a
process which is
running and the
specialty on command
kill 0?

Answer

With the help of kill command we can terminate the process.


Syntax: kill pid
Kill 0 - kills all processes in your system except the login
shell.

How to terminate a
process which is
running and the
specialty on command
kill 0?

Answer

With the help of kill command we can terminate the process.


Syntax: kill pid
Kill 0 - kills all processes in your system except the login
shell.

53

How to sfind free


space in unix/linux

Answer

Df and du commands are used for checking free space on disk


.
df -h or df -Humanreadable gives human readable format of
free space.

What is the difference


between soft link and
hard link in unix
operating system ?

Hard Links :
1. All Links have same inode number.
2.ls -l command shows all the links with the link
column(Second) shows No. of links.
3. Links have actual file contents
4.Removing any link ,just reduces the link count , but doesn't
affect other links.
Answer

Soft Links(Symbolic Links) :


1.Links have different inode numbers.
2. ls -l command shows all links with second column value 1
and the link points to original file.
3. Link has the path for original file and not the contents.
4.Removing soft link doesn't affect anything but removing
original file ,the link becomes "dangling" link which points to
nonexistant file.

to concatenate
(attach) two strings?

For concatenating two string we use cat command.


Answer

Ex:- cat str1 str2

54

Explain the UNIX


Kernel.

Answer

UNIX Kernel is heart of the operating system. UNIX kernal is


loaded first when UNIX system is booted. It handles
allocation of devices, cpu, memory from that ponint on.

How many prompts are


available in a UNIX
system?

Unix/ Linux Supports four Prompts PS1, PS2, PS3, PS4


Answer

#,@,$,% are 4 prompts

You might also like