Unix Lab Manual
Unix Lab Manual
Unix Lab Manual
INDEX
3
2 Introduction About Lab
5
3 Guidelines to Students
7
4 List of Syllabus Programs (JNTU)
10
5 Description about UNIX commands
20
6 Discription about shells
22
6 Solutions for Programs
35
7 Viva Questions and Answers
55
8 References
2
LAB OBJECTIVE
Upon successful completion of this Lab the student will be able to:
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.
3. 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.
4. Copy, move, and delete files and directories
5. Write moderately complex Shell scripts.
RAM : 256 MB
Hard Disk : 40 GB
Software
All systems are configured in DUAL BOOT mode i.e, Students can boot from
Windows XP or Linux as per their lab requirement.
This is very useful for students because they are familiar with different
Operating Systems so that they can execute their programs in different
programming environments.
Oracle 9i client version is installed in all systems. On the server, account for each
student has been created.
This is very useful because students can save their work ( scenarios’,
pl/sql programs, data related projects ,etc) in their own accounts. Each student
work is safe and secure from other students.
Latest Technologies like DOT NET and J2EE are installed in some
systems. Before submitting their final project, they can start doing mini
project from 2nd year onwards.
4
Systems are assigned numbers and same system is allotted for students when they
do the lab.
5
Guidelines to Students
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.
For example, the script file show has the following lines
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.
For example, the script file show has the following lines
$ show
Here is the date and time
Sat jun 03 13:40:15 PST 2006
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.
main()
{
printf(“ welcome to GNEC “);
}
$ cc show.c
If the program is okay, the compiled version is placed in a file called a.out
$ a.out
Welcome to GNEC
7
WEEK1
Session 1
Session 2
WEEK2
WEEK3
WEEK4
a) pipe ur /etc/passwd file to awk and print out the home directory of each user.
b) Develop an interactive grep script that asks for a word and a file name and then
tells how many lines contain that word
c) Repeat
d) Part using awk
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
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.
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
9
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
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.
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.
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) file type
2) number of links
3) read, write and execute permissions
4) time of last access
WEEK 11
WEEK 12
Command CAT
Syntax cat [argument] [specific file]
cat /etc/profile
Command pwd
Syntax pwd
directory.
Command ls
Syntax ls [options] [names]
ls -a
ls -l
ls -al
ls -al /usr
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 mv
Syntax mv [options] sources target
mv Chapter1 garbage
mv Chapter1 /tmp
mv tmp tmp.old
-f, --force
ignore nonexistent files, never prompt
-i, --interactive
prompt before any removal
-v, --verbose
explain what is being done
rm *.html
rm index*
rm -r new-novel
Command cp
Syntax cp [options] file1 file2
cp /usr/fred/Chapter1 .
directory.
cp /usr/fred/Chapter1 /usr/mary
Command grep
Syntax grep [options] regular expression [files]
grep 'joe' *
Command mkdir
Syntax mkdir [options] directory name
mkdir /usr/fred/tmp
mkdir -p /home/joe/customer/acme
Command rmdir
Syntax rmdir [options] directories
Description The "rm" command is used to remove files and
directories. (Warning - be very careful when removing
17
rm *.html
rm index*
rm -r new-novel
cd /usr/fred
cd /u*/f*
cd
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.
Command kill
Syntax kill [options] IDs
Description 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 ps
Syntax ps [options]
system.
Examples ps
ps -f
ps -e
ps -ef
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
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.
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
21
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.
22
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.
23
SOLUTIONS:
WEEK1
Session 1
Sol:
$ 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. Log into the system
2. Open the file created in session 1
3. Add some text
4. Change some text
5. delete some text
6. Save the changes
7. Logout of the system
Sol:
$ login: <user name>
$ password: ******
$ vi myfile
: wq
24
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
Sol:
$ cat –c1-14
WEEK3
Sol:
$ echo $SHELL
csh
$ who >| myfile1
$ more myfile1
$ date|who >myfile2
$ more myfile2
26
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 Clothing 3141
1 Computers 9161
1 Textbooks 21312
2 Clothing 3252
2 Computers 1232
2 Supplies 2242
2 Text books 15462
O/P:
2 Computers 1232
27
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:
Output:
Directory
28
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:
I/P: line1
line2
line3
line4
line5
O/P: line1
line5
(b) Sol:
i=1
while [ $i -le $# ]
do
done
29
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
(b)
a=$1
b=$2
c=pow($a,$b)
echo”$c”
30
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
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
#!/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
32
(b) PROGRAM
(c) PROGRAM
O/P:
Enter the String: Now is the time
The String length : 15
33
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. file type
2. number of links
3. read, write and execute permissions
4. time of last access
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();
}
34
WEEK 11
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);
}
}
35
WEEK 12
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);
}
36
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
How can you tell what shell you are running on UNIX
system?
cmp - Compares two files byte by byte and displays the first
mismatch
diff - tells the changes to be made to make the files identical
Yes, it stands for ‘disk usage’. With the help of this command
you can find the disk capacity and free space of the disk.
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 […]
Use ‘su’ command. The system asks for password and when
valid entry is made the user gains super user (admin) privileges.
During the fork() system call the Kernel makes a copy of the parent process’s address
space and attaches it to the child process.But the vfork() system call do not makes any
copy of the parent’s address space, so it is faster than the fork() system call. The child
process as a result of the vfork() […]
What are the entities that are swapped out of the main
memory while swapping the process out of the main
memory?
41
Is the Process before and after the swap are the same? Give
reason.
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 child’s exit status. To be able to get this
information, the parent calls `wait()‘; In the […]
What is a shell?
How do you create special files like named pipes and device
files?
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.
46
Symbolic link ‘is’ a file that only contains the name of another
file.Operation […]
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 child’s exit status. To be able to get this
information, the parent calls `wait()‘; In the […]
What is a shell?
48
How do you create special files like named pipes and device
files?
What is a FIFO?
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 is ‘inode’?
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 […]
What is ‘inode’?
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 […]
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.
51
$cat >file means to create a new file $cat file means to open
an existing file.
cat > file it means creating file for file cat file it means used to
display the file content
Which command is
used to delete all files
in the current directory
and all its sub-
directories?
# rm -rf *
Answer
Answered By: Amit Shiknis Date: 12/25/2007
rm -r *
52
Yes you are correct. It stands for listing the files Chapter with
Answer suffix 1 to 5 but it will display the files in columns as with-x
option.
Device filles are of 2 types --- charcater device file and block
device file
How to switch to a
super user status to
gain privileges?
Use ‘su’ command. The system asks for password and when
Answer valid entry is made the user gains super user (admin)
privileges.
TERM,SHELL, MAIL
$>echo $TERM
ansi
at the prompt.
What is redirection?
How to terminate a
process which is
running and the
specialty on command
kill 0?
How to terminate a
process which is
running and the
specialty on command
kill 0?
Hard Links :
4.Removing any link ,just reduces the link count , but doesn't
affect other links.
3. Link has the path for original file and not the contents.
to concatenate
(attach) two strings?
REFERENCES:
Books:
1)Introduction to UNIX & SHELL programming, M.G. Venkatesh Murthy, Pearson Education.
3)Unix for programmers and users, 3rd edition, Gaham Glass & K. Ables, pearson education.
4)Unix and shell Programming –A text book, B.A. Forouzan & R.F. Giberg, Thomson.