0% found this document useful (0 votes)
137 views36 pages

OSV Lab Manual

The document provides summaries of 14 common UNIX/Linux commands: 1. cal displays a calendar for a given month and year. 2. clear clears the terminal screen. 3. pwd displays the path of the current working directory. 4. ls lists files and directories in the current directory. It has options to change the output format. 5. mkdir creates new directories. It has options like creating parent directories if needed.

Uploaded by

MAKVANA HARSH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views36 pages

OSV Lab Manual

The document provides summaries of 14 common UNIX/Linux commands: 1. cal displays a calendar for a given month and year. 2. clear clears the terminal screen. 3. pwd displays the path of the current working directory. 4. ls lists files and directories in the current directory. It has options to change the output format. 5. mkdir creates new directories. It has options like creating parent directories if needed.

Uploaded by

MAKVANA HARSH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIX/LINUX Basic Commands

Practical No: Date: _______________

Aim: Execute Unix/Linux Command and Describe the Output.

Theory

1) cal:- Displays a calendar


Syntax:- cal [options] [ month ] [year]
Description :-
 cal displays a simple calendar. If arguments are not specified, the current month is
displayed. The switching options are as follows:

-1 Display single (current) month output. (This is the default.)


-3 Display prev/current/next month output
-s Display Sunday as the first day of the week (This is the default.)
-m Display Monday as the first day of the week
-j Display Julian dates (days one-based, numbered from January 1)
-y Display a calendar for the current year

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

2) clear :- It clears the terminal screen.


Syntax :- clear
Description :-
 Clear clears your screen if this is possible, including its scroll back buffer.
 Clear ignores any command-line parameters that may be present.

3) pwd :- Displays path from root to current directory


Syntax :- pwd [options]

Example:-
$ pwd
/home/kumar/progs

4) cd:- It is used to change the directory.


Syntax :- cd [directory]

Gandhinagar Institute of Technology 3141601 OSV


Description :-
 Used to go back one directory on the majority of all UNIX shells. It is important that
the space be between the cd and directory name

Example:-
$ pwd
/home/kumar
$ cd progs
$ pwd
/home/kumar/progs
$ cd ..
/home/kumar

5) ls:- Lists the contents of a directory


Syntax :- ls [options]
Description :-

-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

Gandhinagar Institute of Technology 3141601 OSV


directory. In this example, the file name is file1.txt

6) exit :- It is used to terminate a program, shell or log you out of a network normally.
Syntax :- exit

7) echo :- It prints the given input string to standard output.


Syntax :- echo string
Example:-
$ echo “hi.. hello unix”
hi.. hello unix

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

-b Prints time of last system boot.

-d print dead processes.


-H Print column headings above the output.

Include idle time as HOURS:MINUTES. An idle time of .


-l indicates activity within the last minute.

-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.

9) who am i:- Print effective userid


Syntax :- who am i
Description: - Print the user name associated with the current effective user id.
Example :-
$ who am i
dietstaffpts/3 2016-02-10 08:52 (: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.

10) mkdir:- This command is used to create a new directory

Gandhinagar Institute of Technology 3141601 OSV


Syntax :- mkdir [options] directory
Description: -

-m Set permission mode (as in chmod)


-p No error if existing, make parent directories as
needed.
-v Print a message for each created directory
Directory The name of the directory that you wish to create

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.

11) rmdir:- It is used to delete/remove a directory and its subdirectories.


Syntax :- rmdir [options..] Directory
Description :-
 It removes only empty directory.

-p Allow users to remove the directory and its parent directories which become
empty.

12) cat:- It is used to create, display and concatenate file contents.


Syntax : - cat [options] [FILE]...

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.

 three uses of the cat command.


1) Create new files.
2) Display the contents of an existing file.
3) Concatenate the content of multiple files and display.
Example :-

$ cat file1.c

 Above syntax will display the content of file1.c

Gandhinagar Institute of Technology 3141601 OSV


$ cat > file1.c
 Above syntax creates file1.c and allow us to insert content for this file.
 After inserting content you can use ctrl+d to exit the file.
 If file with same name exist then it will overwrite that file.

$ cat file1.c
Process management
Memory Management
File Management

$ cat file1.c >> file2.c


 It can concatenate the contents of two files. For this you have to use append
output redirection operator.
 The contents of file2.cwill be appended to file1.c.

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.

14) rm:- It is used to remove/delete the file from the directory.


Syntax :- rm [options..] [file|directory]
Description:-
 Files can be deleted with rm. It can delete more than one file with a single
invocation. For deleting a single file we have to use rm command with filename
to be deleted.
 Deleted file can’t be recovered. rm can’t delete the directories. If we want to
remove all the files from the particular directory we can use the * symbol.

-f Ignore nonexistent files, and never prompt before removing.


-i Prompt before every removal.
Examlple :-

$ 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

Gandhinagar Institute of Technology 3141601 OSV


prompted before rm removes it.
$ rm -f myfile.txt
 Remove the file myfile.txt. You will not be prompted, even if the file is write-
protected; if rm can delete the file, it will.
$ rm -f *
 Remove all files in the working directory. rm will not prompt you for any
reason before deleting them.
$ rm -i *
 Attempt to remove every file in the working directory, but prompt before each
file to confirm.

15) mv:- It is used to move/rename file from one directory to another.


Syntax :- mv [options] oldname newname
Description:-
 mv command which is short for move.
 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.
 mv has two functions: it renames a file and it moves a group of files to a
different directory. Mv doesn’t create a copy of the file , it merely renames it.
No additional space is consumed on disk during renaming. For example if we
rename a file os to os1 and then if we try to read file os we will get error message
as it is renamed to os1 there is no existence of file named os.
Example:-
$ cat file1
Memory
Process
Files
$ mv file1 file2
 rename file1 to file2
 If the destination file doesn’t exist it will be created. mv can also be used to
rename a directory. A group of files can also be moved to a directory. mv
doesn’t prompt for overwriting destination file if it exists.

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.

-i Ignore case distinctions


-f Ignore nonexistent files, and never prompt before removing.
-v Invert the sense of matching, to select non-matching lines.
-w Select only those lines containing matches that form whole words.
-x Select only matches that exactly match the whole line.

Gandhinagar Institute of Technology 3141601 OSV


-c print a count of matching lines for each input file.

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

2. Perform following advance commands and filters of Linux/UNIX.


1. finger 2. grep 3.egrape 4.fgrape 5. script 6. expr 7.sort 8. More

Review Questions:
1. Explain different commands in UNIX/Linux.
2. What is shell programming?

Gandhinagar Institute of Technology 3141601 OSV


[This page is intentionally left blank]

Gandhinagar Institute of Technology 3141601 OSV


VI Editor
Practical No: Date: _______________

Aim: Create shell script using VI Editor.

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.

Gandhinagar Institute of Technology 3141601 OSV


Operation Modes
While working with the vi editor, we usually come across the following two modes −
 Command mode − This mode enables you to perform administrative tasks such as
saving the files, executing the commands, moving the cursor, cutting (yanking) and
pasting the lines or words, as well as finding and replacing. In this mode, whatever
you type is interpreted as a command.
 Insert mode − This mode enables you to insert text into the file. Everything that's
typed in this mode is interpreted as input and placed in the file.
vi always starts in the command mode. To enter text, you must be in the insert mode for
which simply type i. To come out of the insert mode, press the Esc key, which will take you
back to the command mode.
Hint − If you are not sure which mode you are in, press the Esc key twice; this will take you
to the command mode. You open a file using the vi editor. Start by typing some characters
and then come to the command mode to understand the difference.
Getting Out of vi
The command to quit out of vi is :q. Once in the command mode, type colon, and 'q', followed
by return. If your file has been modified in any way, the editor will warn you of this, and not
let you quit. To ignore this message, the command to quit out of vi without saving is :q!. This
lets you exit vi without saving any of the changes.
The command to save the contents of the editor is :w. You can combine the above command
with the quit command, or use :wq and return.
The easiest way to save your changes and exit vi is with the ZZ command. When you are in
the command mode, type ZZ. The ZZ command works the same way as the :wq command.
If you want to specify/state any particular name for the file, you can do so by specifying it
after the :w. For example, if you wanted to save the file you were working on as another
filename called filename2, you would type :w filename2 and return.
Moving within a File
To move around within a file without affecting your text, you must be in the command mode
(press Esc twice). The following table lists out a few commands you can use to move around
one character at a time −
S.No. Command & Description

1 K Moves the cursor up one line

2 J Moves the cursor down one line

3 H Moves the cursor to the left one character position

4 L Moves the cursor to the right one character position

Gandhinagar Institute of Technology 3141601 OSV


The following points need to be considered to move within a file −
 vi is case-sensitive. You need to pay attention to capitalization when using the
commands.
 Most commands in vi can be prefaced by the number of times you want the
action to occur. For example, 2jmoves the cursor two lines down the cursor
location.
There are many other ways to move within a file in vi. Remember that you must be in the
command mode (press Esc twice). The following table lists out a few commands to move
around the file −

Given below is the list of commands to move around the file.


Control Commands
The following commands can be used with the Control Key to perform functions as given in
the table below −
Given below is the list of control commands.
Editing Files
To edit the file, you need to be in the insert mode. There are many ways to enter the insert
mode from the command mode −
S.No. Command & Description

1 I Inserts text before the current cursor location

2 I Inserts text at the beginning of the current line

3 A Inserts text after the current cursor location

4 A Inserts text at the end of the current line

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

1 X Deletes the character under the cursor location

2 X Deletes the character before the cursor location

3 Dw Deletes from the current cursor location to the next word

Gandhinagar Institute of Technology 3141601 OSV


4 d^ Deletes from the current cursor position to the beginning of the line

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

7 Dd Deletes the line the cursor is on

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 –

S.No. Command & Description

1 Cc Removes the contents of the line, leaving you in insert mode.

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.

Copy and Paste Commands


You can copy lines or words from one place and then you can paste them at another place
using the following commands −
S.No. Command & Description

1 Yy Copies the current line.

2 Yw Copies the current word from the character the lowercase w cursor is on, until
the end of the word.

Gandhinagar Institute of Technology 3141601 OSV


3 P Puts the copied text after the cursor.

4 P Puts the yanked text before the cursor.

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.

Gandhinagar Institute of Technology 3141601 OSV


[This page is intentionally left blank]

Gandhinagar Institute of Technology 3141601 OSV


Decision-Making in UNIX/Linux

Practical No: Date: _______________

Aim: Use of conditional statement in UNIX/LINUX.

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.

Gandhinagar Institute of Technology 3141601 OSV


Example
a=10
b=20

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

Gandhinagar Institute of Technology 3141601 OSV


if...elif...else...fi statement
The if...elif...fi statement is the one level advance form of control statement that allows Shell
to make correct decision out of several conditions.

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.

Gandhinagar Institute of Technology 3141601 OSV


Review Questions:

1. What is if.. fi statement?


2. What is difference between if...else...fi and if...elif...else...fi statement?

Gandhinagar Institute of Technology 3141601 OSV


Case Statements in UNIX/Linux

Practical No: Date: _______________

Aim: Use of case statement 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."
;;

Gandhinagar Institute of Technology 3141601 OSV


esac
Upon execution, you will receive the following result −
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.

Gandhinagar Institute of Technology 3141601 OSV


Loops in UNIX/Linux

Practical No: Date: _______________

Aim: Use of loops in Unix/Linux.

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 −

 The while loop


 The for loop
 The until loop
 The select loop

The while loop


The while loop enables you to execute a set of commands repeatedly until some condition
occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
Syntax
while command
do
Statement(s) to be executed if command is true
done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are
executed. If command is false then no statement will be executed and the program will jump
to the next line after the done statement.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine −

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

Gandhinagar Institute of Technology 3141601 OSV


9

The for loop


The for loop operates on lists of items. It repeats a set of commands for every item in a list.
Syntax
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters separated
by spaces (words). Each time the for loop executes, the value of the variable var is set to the
next word in the list of words, word1 to wordN.
Example
Here is a simple example that uses the for loop to span through the given list of numbers −

#!/bin/sh

for var in 0 1 2 3 4 5 6 7 8 9

do

echo $var

done

Upon execution, you will receive the following result −

0
1
2
3
4
5
6
7
8
9

The until loop


The while loop is perfect for a situation where you need to execute a set of commands while
some condition is true. Sometimes you need to execute a set of commands until a condition is
true.
Syntax
until command
do
Statement(s) to be executed until command is true

Gandhinagar Institute of Technology 3141601 OSV


done
Here the Shell command is evaluated. If the resulting value is false, given statement(s) are
executed. If the command is true then no statement will be executed and the program jumps
to the next line after the done statement.
Example
Here is a simple example that uses the until loop to display the numbers zero to nine −

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

The select loop


The select loop provides an easy way to create a numbered menu from which users can select
options. It is useful when you need to ask the user to choose one or more items from a list of
choices.
Syntax
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters separated
by spaces (words). Each time the for loop executes, the value of the variable var is set to the
next word in the list of words, word1 to wordN.
For every selection, a set of commands will be executed within the loop. This loop was
introduced in ksh and has been adapted into bash. It is not available in sh.
Example
Here is a simple example to let the user select a drink of choice −

select DRINK in tea cofee water juice appe all none


do
case $DRINK in

Gandhinagar Institute of Technology 3141601 OSV


tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
The menu presented by the select loop looks like the following −

$./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

$PS3 = "Please make a selection => " ; export PS3


$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$
Nesting Loops
All the loops support nesting concept which means you can put one loop inside another similar
one or different loops. This nesting can go up to unlimited number of times based on your
requirement.
Here is an example of nesting while loop. The other loops can be nested based on the
programming requirement in a similar way −

Gandhinagar Institute of Technology 3141601 OSV


Nesting while Loops
It is possible to use a while loop as part of the body of another while loop.
Syntax
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true

while command2 ; # this is loop2, the inner loop


do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true


done

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.

Gandhinagar Institute of Technology 3141601 OSV


[This page is intentionally left blank]

Gandhinagar Institute of Technology 3141601 OSV


Command line arguments in shell script

Practical No: Date: _______________

Aim: To study about command line arguments in shell script.

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.

Why Command Line arguments required?


1. Telling the command/utility which option to use.
2. Informing the utility/command which file or group of files to process (reading/writing of
files).

Example
In this example, we are going to write a script that expects the user to provide two numbers.

Gandhinagar Institute of Technology 3141601 OSV


The script then uses the two numbers as operands of the basic mathematical operations.
[root@student ~] # cat –n calc2.sh
1 A=’

Let’s execute it:

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?

Gandhinagar Institute of Technology 3141601 OSV


Executable Files and Directories

Practical No: Date: _______________

Aim: To study about Executable files and directories.

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.

Different file and directory commands:-

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

Gandhinagar Institute of Technology 3141601 OSV


size, Modified date and time and filename.
-t Lists in order of last modification time.
-a Lists all entries including hidden files.
-d Lists directory files instead of contents.
-p Puts slash at the end of each directories.
-u List in order of last access time.
-i Display inode information.

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:

Gandhinagar Institute of Technology 3141601 OSV


The Syntax is
cmp [options..] file1 file2

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.

11) paste COMMAND:


paste command is used to paste the content from one file to another file. It is also used to
set column format for each line.

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 .

12) rmdir COMMAND:


rmdir command is used to delete/remove a directory and its subdirectories.

Gandhinagar Institute of Technology 3141601 OSV


SYNTAX:
The Syntax is
rmdir [options..] Directory

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?

Gandhinagar Institute of Technology 3141601 OSV


About AWK

Practical No: Date: _______________

Aim: To study about AWK.

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.

The essential organization of an AWK program follows the form:

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.

The AWK program below:

BEGIN { print "START" }


{ print }
END { print "STOP" }

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:

BEGIN { print "File\tOwner"," }


{ print $8, "\t", $3}
END { print " - DONE -" }

Functions in awk :-
index(string,search)
length(string)
split(string,array,separator)
substr(string,position)
substr(string,position,max)
tolower(string)
toupper(string)

Gandhinagar Institute of Technology 3141601 OSV


Exercise:
1. Write an awk program using function, which convert each word in a given text into
capital.
2. Write a shell script to validate the entered date.(dd-mm-yyyy)

Review Question:
1. What is awk?
2. What is validation?

Gandhinagar Institute of Technology 3141601 OSV


Process Creation

Practical No: Date: _______________

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

Unix Process Creation

 Unix fork() creates a process

 Creates a new address space


 Copies text, data, & stack into new adress space
 Provides child with access to open files

 Unix exec() allows a child to run a new program


 Unix wait() allows a parent to wait for a child to terminate

Gandhinagar Institute of Technology 3141601 OSV


Note

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.

Gandhinagar Institute of Technology 3141601 OSV

You might also like