OSV Lab Manual
OSV Lab Manual
Theory
Example:-
$cal or
$cal 02 2016
Feb 2016
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29
Example:-
$ pwd
/home/kumar/progs
Example:-
$ pwd
/home/kumar
$ cd progs
$ pwd
/home/kumar/progs
$ cd ..
/home/kumar
-a Shows you all files, even files that are hidden (these files begin with a dot.)
-A List all files including the hidden files. However, does not display the working
directory (.) or the parent directory (..).
-d If an argument is a directory it only lists its name not its contents
-l Shows you huge amounts of information (permissions, owners, size, and when
last modified.)
-p Displays a slash ( / ) in front of all directories
-r Reverses the order of how the files are displayed
-R Includes the contents of subdirectories
Example:-
$ ls – l
-rw-r----- 1 student student 23 Jan 16 15:27 file1.txt
Field Explanation:
If first character is – then it is normal file
If it is d then it is directory
Field 1 – File Permissions: Next 9 character specifies the files permission. Each 3
characters refers to the read, write, execute permissions for user, group and world In
this example, -rw-r—– indicates read-write permission for user, read permission for
group, and no permission for others.
Field 2 – Number of links: Second field specifies the number of links for that file.
In this example, 1 indicates only one link to this file.
Field 3 – Owner: Third field specifies owner of the file. In this example, this file is
owned by username ‘student’.
Field 4 – Group: Fourth field specifies the group of the file. In this example, this file
belongs to ”student’ group.
Field 5 – Size: Fifth field specifies the size of file. In this example, ’23′ indicates the
file size.
Field 6 – Last modified date & time: Sixth field specifies the date and time of the
last modification of the file. In this example, ‘Jan 16 15:27′ specifies the last
modification time of the file.
Field 7 – File or directory name: The last field is the name of the file or
6) exit :- It is used to terminate a program, shell or log you out of a network normally.
Syntax :- exit
8) who :- who command can list the names of users currently logged in, their terminal, the
time they have been logged in, and the name of the host from which they have logged in.
Syntax :- who [options] [file]
Description:-
am i Print the username of the invoking user, The 'am' and 'i' must be space
separated
-m Same as who am i.
-q Prints only the usernames and the user count/total no of users logged in.
Example :-
$ who
dietstaffpts/1 2016-02-20 22:42 (:0.0)
dietstaffpts/2 2016-02-20 09:30 (:0.0)
Here first column shows user name, second shows name of the terminal the user
is working on. Third& fourth column shows date and time of logging, last
column shows machine name.
Example:-
$ mkdir aaa
The above command will create directory named aaa under the current directory.
We can also create number of subdirectories with one mkdir command.
-p Allow users to remove the directory and its parent directories which become
empty.
Description:-
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
Non-printing characters (with the exception of tabs, new-lines and form-feeds)
-v
are
printed visibly.
$ cat file1.c
$ cat file1.c
Process management
Memory Management
File Management
13) cp:- cp command copy files from one location to another. If the destination is an
existing file, then the file is overwritten; if the destination is an existing directory, the
file is copied into the directory (the directory is not overwritten).
Syntax :- cp [options]... source destination
Description:-
Here, after cp command contents of both source file and destination file files
are the same.
It will copy the content of source file to destination file.
If the destination file doesn’t exist, it will be created.
If it exists then it will be overwritten without any warning.
If there is only one file to be copied then destination can be the ordinary file
or the directory file.
Example:-
$ cp file1 file2
The above cp command copies the content of file1.php to file2.php.
$ rm myfile.txt
Remove the file myfile.txt. If the file is write-protected, you will be prompted
to confirm that you really want to delete it.
$ rm *
Remove all files in the working directory. If it is write-protected, you will be
16) grep:- It selects and prints the lines from a file which matches a given string or pattern.
Syntax:- grep [options] pattern [file]
Description:-
This command searches the specified input fully for a match with the supplied pattern
and displays it.
While forming the patterns to be searched we can use shell match characters, or
regular expressions.
Let us begin with the simplest example of usage of grep.
Example :-
$ grep "Error" logfile.txt
This searches for the string "Error" in the log file and prints all the lines that has the
word "Error".
$ grep "string" file1 file2
Searching for a string in multiple files.
$ grep -i "UNix" file.txt
The -i option enables to search for a string case insensitively in the give file. It matches
the words like "UNIX", "Unix", "unix".
$ grep -w "world" file.txt
By default, grep matches the given string/pattern even if it found as a substring in a file.
The -w option to grep makes it match only the whole words.
$ grep -c "sting" file.txt
We can find the number of lines that matches the given string/pattern
$ grep -l "string" *
We can just display the files that contain the given string/pattern.
$ grep -n "string" file.txt
We can make the grep command to display the position of the line which contains the
matched string in a file using the -n option
Exercise:
1. Perform following commands in UNIX/LINUX.
1.ps 2. ls 3. man 4. head 5. tail 6. tty 7. cal 8. diff 9. cut 10. pwd 11. who 12. paste
13. find 14. kill 15. date 16. history 17. cmp 18. wc 19. touch 20. cat 21. tty 22. cp 23.
mv 24. mkdir 25. cd 26. rmdir 27. rm 28. set 29. chmod
Review Questions:
1. Explain different commands in UNIX/Linux.
2. What is shell programming?
Theory
There are many ways to edit files in Unix. Editing files using the screen-oriented text
editor vi is one of the best ways. This editor enables you to edit lines in context with other
lines in the file.
vi is generally considered the de facto standard in Unix editors because −
It's usually available on all the flavors of Unix system.
Its implementations are very similar across the board.
It requires very few resources.
It is more user-friendly than other editors such as the edor the ex.
You can use the vi editor to edit an existing file or to create a new file from scratch. You can
also use this editor to just read a text file.
Starting the vi Editor
The following table lists out the basic commands to use the vi editor −
S.No. Command & Description
1 vi filename
Creates a new file if it already does not exist, otherwise opens an existing file.
2 vi -R filename
Opens an existing file in the read-only mode.
3 view filename
Opens an existing file in the read-only mode.
Following is an example to create a new file testfile if it already does not exist in the current
working directory −
$vi testfile
The above command will generate the following output −
|
~
~
~
~
"testfile" [New File]
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused line.
If a line does not begin with a tilde and appears to be blank, there is a space, tab, newline, or
some other non-viewable character present.
You now have one open file to start working on. Before proceeding further, let us understand
a few important concepts.
5 O Creates a new line for text entry below the cursor location
6 O Creates a new line for text entry above the cursor location
Deleting Characters
Here is a list of important commands, which can be used to delete characters and lines in an
open file −
S.No. Command & Description
5 d$ Deletes from the current cursor position to the end of the line
6 D Deletes from the cursor position to the end of the current line
As mentioned above, most commands in vi can be prefaced by the number of times you want
the action to occur. For example, 2x deletes two characters under the cursor location
and 2dddeletes two lines the cursor is on.
It is recommended that the commands are practiced before we proceed further.
Change Commands
You also have the capability to change characters, words, or lines in vi without deleting them.
Here are the relevant commands –
2 Cw Changes the word the cursor is on from the cursor to the lowercase w end of the
word.
3 R Replaces the character under the cursor. vi returns to the command mode after the
replacement is entered.
4 R Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting.
5 S Replaces the current character with the character you type. Afterward, you are left
in the insert mode.
6 S Deletes the line the cursor is on and replaces it with the new text. After the new
text is entered, vi remains in the insert mode.
2 Yw Copies the current word from the character the lowercase w cursor is on, until
the end of the word.
Exercise:
1. Write a shell script to print “Hello World”.
Review Questions:
1. What is VI Editor?
2. What is Shell script?
3. Write a Shell script with an example.
Theory
While writing a shell script, there may be a situation when you need to adopt one path out of
the given two paths. So you need to make use of conditional statements that allow your
program to make correct decisions and perform the right actions.
Unix Shell supports conditional statements which are used to perform different actions based
on different conditions. We will now understand two decision-making statements here
The if...else statement
The case...esac statement
The if...else statements
If else statements are useful decision-making statements which can be used to select an option
from a given set of options.
Unix Shell supports following forms of if…else statement −
if...fi statement
if...else...fi statement
if...elif...else...fi statement
if...fi statement
The if...fi statement is the fundamental control statement that allows Shell to make decisions
and execute statements conditionally.
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false then no statement would be
executed. Most of the times, comparison operators are used for making decisions.
It is recommended to be careful with the spaces between braces and expression. No space
produces a syntax error.
If expression is a shell command, then it will be assumed true if it returns 0after execution. If
it is a Boolean expression, then it would be true if it returns true.
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
The above script will generate the following result −
a is not equal to b
if...else...fi statement
The if...else...fi statement is the next form of control statement that allows Shell to execute
statements in a controlled way and make the right choice.
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false, then no statement will be executed.
Example
The above example can also be written using the if...else statement as follows −
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
Upon execution, you will receive the following result −
a is not equal to b
Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
This code is just a series of if statements, where each if is part of the elseclause of the previous
statement. Here statement(s) are executed based on the true condition, if none of the condition
is true then else block is executed.
Example
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
Upon execution, you will receive the following result −
a is less than b
Exercise:
1. Write a shell script to generate marksheet of a student. Take 3 subjects, calculate and
display total marks, percentage and Class obtained by the student.
2. Write a shell script to find the largest among the 3 given numbers in UNIX / Linux.
Theory
You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.
Shell supports case...esac statement which handles exactly this situation, and it does so more
efficiently than repeated if...elif statements.
Syntax
The basic syntax of the case...esac statement is to give an expression to evaluate and to execute
several different statements based on the value of the expression.
The interpreter checks each case against the value of the expression until a match is found. If
nothing matches, a default condition will be used.
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Here the string word is compared against every pattern until a match is found. The statement(s)
following the matching pattern executes. If no matches are found, the case statement exits
without performing any action.
There is no maximum number of patterns, but the minimum is one.
When statement(s) part executes, the command ;; indicates that the program flow should jump
to the end of the entire case statement. This is similar to break in the C programming language.
Example
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
Exercise:
1. Write Script, using case statement to perform basic math operation as follows
a) + addition
b) – subtraction
c) x multiplication
d) / division
2. Write a menu driven shell script which will print the following menu and execute the
given task.
a) Display calendar of current month
b) Display today’s date and time
c) Display usernames those are currently logged in the system
d) Display your name at given x, y position
e) Display your terminal number
f) Exit
Review Question
1. What is use case statement?
2. Difference between nested if and case statement.
Theory
A loop is a powerful programming tool that enables you to execute a set of commands
repeatedly. In this chapter, we will examine the following types of loops available to shell
programmers −
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
0
1
2
3
4
5
6
7
8
9
a=0
until [ ! $a -lt 10 ]
do
echo $a
a = `expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
You can change the prompt displayed by the select loop by altering the variable PS3 as follows
−
Exercise:
1. Write a shell script to find factorial of a given number in Unix/Linux.
2. Write a shell script which will accept a number b and display first n prime numbers as
output
3. Writ a shell script which will generate first n Fibonacci numbers like 1,1,2,3,5,13…….
4. Write a shell script which will accept different numbers and find sum of its digit.
5. Write a shell script to check entered string is palindrome or not
Review Question:
1. What is use of Loops in shell script?
2. Difference between while and until loops.
3. Difference between while and for loops.
Theory
Command line arguments (also known as positional parameters) are the arguments specified at
the command prompt with a command or script to be executed. The locations at the command
prompt of the arguments as well as the location of the command, or the script itself, are stored
in corresponding variables. These variables are special shell variables. Below picture will help
you understand them.
Example
In this example, we are going to write a script that expects the user to provide two numbers.
Exercise:
1. Write a shell script to read n numbers as command arguments as sort them in
descending order.
Review Question:
1. What is command line argument?
2. Why Command Line arguments required?
Theory
In Unix, all data are stored in repositories called files. For example, the RESOLVE/C++
programs that you write in this course will be stored as Unix files. You could also use files to
store any reports that you write or to save the e-mail that you receive.
Like in the "real" world, it is not a good idea to have lots of files "lying around" in a
disorganized manner. Unix allows you to organize your files into directories. A "directory" is
a location where files are kept in a list. For instance, you could create a directory to store all
your files for the first lab and call it Lab1. You could create another directory called Lab2 to
store your files for the second lab. If you are already familiar with either Apple Macintosh
computers or Windows File Manager, just think of UNIX directories as being the same as
folders.
When you login to a UNIX system, the system puts you in your home directory. Your home
directory is the directory that is assigned to you to store all your files. UNIX has commands
that you can use to create and delete files and directories within your home directory. Unix
also gives you commands to change from your home directory to other directories. The
directory that you're in at any given point of time is called your current working directory.
1) pwd COMMAND:
pwd - Print Working Directory. pwd command prints the full filename of the current
working directory.
SYNTAX:
The Syntax is
pwd [options]
2) cd COMMAND:
cd command is used to change the directory.
SYNTAX:
The Syntax is
cd [directory | ~ | ./ | ../ | - ]
3) ls COMMAND:
ls command lists the files and directories under current working directory.
SYNTAX:
The Syntax is
ls [OPTIONS]... [FILE]
OPTIONS:
-l Lists all the files, directories and their mode, Number of links, owner of the file, file
4) rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
SYNTAX:
The Syntax is
rm [options..] [file | directory]
OPTIONS:
-f Remove all files in a directory without prompting the user.
-I Interactive. With this option, rm prompts for confirmation before removing any files.
5) mv COMMAND:
mv command which is short for move. It is used to move/rename file from one directory to
another. mv command is different from cp command as it completely removes the file
from the source and moves to the directory specified, where cp command just copies the
content from one file to another.
SYNTAX:
The Syntax is
mv [-f] [-i] oldname newname
OPTIONS:
-f This will not prompt before overwriting (equivalent to -- reply=yes). mv -f will move
the file(s) without prompting even if it is writing over an existing target.
-i Prompts before overwriting another file.
6) cat COMMAND:
cat linux command concatenates files and print it on the standard output.
SYNTAX:
The Syntax is
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
7) cmp COMMAND:
cmp linux command compares two files and tells you which line numbers are different.
SYNTAX:
OPTIONS:
- c Output differing bytes as characters.
- l Print the byte number (decimal) and the differing byte values (octal) for each difference.
- s Prints nothing for differing files, return exit status only.
8) cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file,
then the file is overwritten; if the destination is an existing directory, the file is copied into
the directory (the directory is not overwritten).
SYNTAX:
The Syntax is
cp [OPTIONS]... SOURCE DEST
9) echo COMMAND:
echo command prints the given input string to standard output.
SYNTAX:
The Syntax is
echo [options..] [string]
10)mkdir COMMAND:
mkdir command is used to create one or more directories.
SYNTAX:
The Syntax is
mkdir [options] directories
OPTIONS:
-m Set the access mode for the new directories.
-p Create intervening parent directories if they don't exist.
-v Print help message for each directory created.
SYNTAX:
The Syntax is
paste [options]
OPTIONS:
-s Paste one file at a time instead of in parallel.
-d Reuse characters from LIST instead of TABs .
OPTIONS:
-p Allow users to remove the directory dir name and its parent directories which become
Empty
Exercise:
1Write a shell script to display all executable files, directories and zero sized files from
current directory.
2 Write a shell script to check entered string is palindrome or not.
Review Question:
1. What is file?
2. What is directory?
Theory:
The AWK utility is an interpreted programming language typically used as a data extraction
and reporting tool. It is a standard feature of most Unix-like operating Systems.
Awk is an excellent tool for building UNIX/Linux shell scripts. AWK is a Programming
language that is designed for processing text-based data, either in files or data streams or using
shells pipes. In other words you can combine awk with shell scripts or directly use at a shell
prompt.
pattern { action }
The pattern specifies when the action is performed. Like most UNIX utilities, AWK is line
oriented. That is, the pattern specifies a test that is performed with each line read as input. If
the condition is true, then the action is taken. The default pattern is something that matches
every line. This is the blank or null pattern.
Two other important patterns are specified by the keywords "BEGIN" and "END." As you
might expect, these two words specify actions to be taken before any lines are read, and after
the last line is read.
adds one line before and one line after the input file. This isn't very useful, but with a simple
change, we can make this into a typical AWK program:
Functions in awk :-
index(string,search)
length(string)
split(string,array,separator)
substr(string,position)
substr(string,position,max)
tolower(string)
toupper(string)
Review Question:
1. What is awk?
2. What is validation?
Aim: Write a program for process creation using C. (Use of gcc compiler).
Theory
Process Creation
Parent process create children processes, which, in turn create other processes, forming a tree
of processes. Generally, process identified and managed via a process identifier (pid)
Resource sharing
Parent and children share all resources
Children share subset of parent’s resources
Parent and child share no resources
Execution
Parent and children execute concurrently
Parent waits until children terminate
Address space
Child duplicate of parent
Child has a program loaded into it
UNIX examples
fork system call creates new process
exec system call used after a fork to replace the process’ memory space with a new
program
Process Creation
In Unix, process creation and management uses multiple, fairly simple system calls. This
provides extra flexability. If needed, the parent process may contain the code for the child
process to run, so that exec() is not always needed. The child may also set up inter-process
communication with the parent, such as with a pipe before running another program.
The only difference between the parent and process after the call to fork() is the return value
from fork().
Exercise:
1. Write a program for process creation using C.
Review Question:
1. What are various IDs associated with a process?
2. List the system calls used for process management.