Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 82

Ex.

No : 1

Date :

Basic Commands in UNIX

Aim

To study and execute the basic UNIX commands

Procedure

9500671930

Command : date

Function : To display the current date and time.

Syntax : $date [+ Format Specifiers]

Example : $date

Formatting directives for the date

Option Meaning

%D The date as MM/DD/YY

%a Abbreviated weekday( sun to sat)

%h Abbreviated month( Jan to Dec )

%j Day of the year(1 to 365 or 366 on leap year)

%w The day of the week(Sunday=0, Monday=1…)

%m The month of the year(1 to 12)

%d The day of the month (1 to 31)

%y Last two digits of the year(0 to 99)


Command : cal

Function : To display the calendar for the specified year or month

Syntax : $cal [month] [year]

Example : $cal - Displays the current month calendar

$cal 01 2010 - Displays the January 2010 calendar.

Command : echo

Function : To display the given text on the screen.

Syntax : $echo text

Example : $echo JAYARAM


Command : man

Function : To Display the manual page of the specified command

Syntax : $man [commad_name]

Example : $man pwd

Command : clear

Function : To clear the screen of the terminal

Syntax : $clear

Example : $clear

Command : tput

Function : To manipulate the screen of the terminal.

Syntax : $tput [options]

Example : $tput clear - Clears the screen and positions the cursor at

the top-left corner in the screen

$tput blink - Used to make the cursor blink. But in some

systems the cursor may become bold and

don’t blink.

Options used with tput command

S.No. Options Purpose

1 clear Cleans the screen

2 longname Displays the complete name of the terminal

3 smso Displays the text typed in the bold face (including the system prompt)
and reverses the background color of the screen in white and
foreground with black

4 rmso Displays the text in normal format (including the system prompt) and
resets the screen color.

5 init Initializes the terminal (in single or multi – user mode)

6 reset Resets the terminal

7 cup RC Used to position the cursor at row number ‘R’ and column number.

8 cols Displays the number of columns for the current terminal.

Command : bc

Function : To perform simple mathematical calculations.

Syntax : $bc [options] [file(s)]

Example : $bc

20+5

25

ctrl + d
Command : who

Function : Gives us the details of who all have logged into the UNIX system

currently

Syntax : $who

Example : $who

Options used with who command

S.No. Options Purpose

This option list only those terminals on which the system is waiting for
1 -l
someone to log

2 -b Displays the date and time the system was brought up.

3 -t Displays the last change to system clock.

4 -u Restricts listings to users currently logged in.

5 -T Displays the state for logged in users.

6 -a Turns on all the above options.

Displays the short form listing which consists of the username terminal
7 -s
number and time fields.

Command : who am i

Function : To know in which terminal the user is currently logged on.

Syntax : $who am i

Example : $who am I

Command : ps

Function : To display information about processes that are alive when we run

the command
Syntax : $ps

Example : $ps [options]

Options used with ps command

S.No. Options Purpose

1 -e Displays information about all processes.

2 -l Lists the information using long format.

3 -F Lists the information using full format.

Restricts listing to data about processes whose user ID are given in the ud
4 -u
list

Restricts listing to data about processes whose process id numbers are


5 -P
given in Proc list.

6 -g Display information of all process of group loads specified in ggrplist.

7 -a Associated with –u, g options


Command : id

Function : To display the numerical value that corresponds to the login name.

Syntax : $id

Example : $id

Command : uname

Function : To display relevant details about the operating system on the

standard output.

Syntax : $uname [options]

Example : $uname -m

Options used with uname command

S.No. Option Purpose

1 -m Displays the machine id

2 -n Displays the name of the operating system

3 -r Displays the release number of the operating system

4 -s Displays the name of the operating system

5 -v Displays the version of the operating system

6 -a Displays the details of all the above five options.

Command : finger

Function : To give more information about user’s identity

Syntax : $finger [user name]

Example : $finger user1


Command : mail

Function : To send a mail to another user and to see a mail received from

another user.

Syntax : $mail [user name]

Example : $mail user2 - To send a mail to user2 from the current

user.

Type the message

ctrl + d

$mail - To see the mail received from other

users.
Ex. No : 2

Date :

Working With Files

A. Files & File Types and The Basic UNIX Commands Used in File Handling

Aim

To study and execute the files & file types and the basic UNIX commands used in file
handling

Procedure

Step1: Create on or more files using cat command.

Step2: Perform copy, link, move, remove and difference operations using the

following commands.

Command : cat

Function : To create a file and to display the content of a specified file.

Syntax : $cat [option] [file name]

Example : $cat > a1 - To create a file called a1.

$cat a1 - To display the contents of a file a1.

Command : cp

Function : To create duplicate copies of ordinary files

Syntax : $cp [source file] [target file]


Example : $cp a1 a2

Command : ln

Function : To make a link to a file.

Syntax : $ln [first name] [second name]

Example : $ln sh1 sh2 - To create an additional name called sh2 for a

file sh1.

Command : mv

Function : To move the contents of one file to another file. The source file no

longer exists in the directory.

Syntax : $mv [source file] [target file]

Example : $mv p1 p2

Command : rm

Function : To remove one or more files from a directory.

Syntax : $rm [option] [file name]

Example : $rm temp/sh1 - Deletes the file sh1 from the directory temp.
Options used with rm command

S.No. Options Purpose

1 -i Asks the user if he wants to delete the file mentioned.

Recursively delete the entire contents of the directory as well as the


2 -r
directory itself.

3 -ir Combination of both i and r.

Command : diff

Function : To display the difference between two files and also the content of

that two files.

Syntax : $diff [file name 1] [file name 2]

Example : $diff a1 a2

Command : find -print

Function : To find the path of all our files in our directories.

Syntax : $find -print

Example : $find -print

Command : find . –name “*sh”

Function : To display the name of all ordinary files from the current directory

whose name ends in “sh”.

Syntax : $find . –name “*sh”

Example : $find . –name “*sh”


Command : find . –name “sh*”

Function : To display the name of all ordinary files from the current directory

whose name begins with “sh”.

Syntax : $find . –name “sh*”

Example : $find . –name “sh*”


B. Sorting The Contents of a File

Aim

To sort the content of files using UNIX commands.

Procedure

1. Create a file using cat command.


2. Display the contents of the created file using cat command.
3. Sort the contents of the file with options.
4. Display the sorted contents of the file using cat command.

Command : sort

Function : To sort the contents of a specified file.

Syntax : $ sort <options> <File name>

Example : $ sort –r a1

Options used with sort command

S.No. Option Purpose

1 -r Sort the data in reverse order

2 -n Sort the data in ascending order

3 -u Duplicate lines are not displayed

4 -c Checks whether the files is sorted

5 -f Folds uppercase into lower case


C. Counting The Number Of Words In A File

Aim

To count the number of words in a file using UNIX commands.

Procedure:

1. Create a file using cat command.


2. Display the contents of the created file using cat command.
3. Count and display the number of words in the specified file using “wc”
command.

Command : wc

Function : To count the number of lines, words and characters in a file.

Syntax : $wc [options] [file name]

Example : $wc –l a1 - Displays the number of lines in the file a1.

$wc –w a1 - Displays the number of words in the file a1.

$wc –c a1 - Displays the number of characters in the file a1.


Ex. No : 3

Date :

Working With Directories

Aim

To study and execute the directory handling commands in UNIX.

Procedure

Command : pwd

Function : To display the full pathname for the current directory.

Syntax : $pwd

Example : $pwd

Command : ls

Function : To display the list of files in the current working directory.

Syntax : $ls [Options] [Arguments]

Example : $ls –l

Options used with ls command

S.No. Options Purpose

1 -l List files in the long format

2 -t Lists in order of last modification time (most recent first)

3 -a List all entries, including the hidden files


4 -d List directory file instead of its contents

5 -p Puts a slash after each directory

6 -u Lists in order of last access time

7 -x It produces a multi – columnar output of file names

8 -F It identifies the directories with / and executable files with * symbols

9 -r Sorts files in reverse order of alphabet

10 -R Recursively lists all files in sub-directories

11 -i Shows node numbers of a file

12 -c Sorts by time of change of the i – node

13 -s Displays number of blocks used by a file

Command : mkdir

Function : To create a new directory.

Syntax : $mkdir [Directory name]

Example : $mkdir exam


Command : cd

Function : To change from working directory to another directory specified.

Syntax : $cd [directory name]

Example : $cd result

Command : rmdir

Function : To remove a directory specified in the command line

Syntax : $rmdir [directory name]

Example : $rmdir exam


Ex. No : 4

Date :

UNIX Editor

Aim

To study and execute the vi editor operations in UNIX.

Procedure

1. vi stands for “visual”

2. Created at university of California at Berkeley by Bill Joy.

3. vi functions are in 3 different mode.

- insert mode
- Command mode
- Ex escape mode
4. insert mode - Helps to insert the text we want to.

5. command mode - Any key pressed by the user is assumed to be commands

by the editior.

6. ex escape mode - Introduced to make the vi and the ex editors compatible.

7. Syntax to create a file using “vi” editor – vi filename

8. Enter key - Executes commands in the ex escape mode and starts a

new line in the insert mode. In the command mode it goes

to the next line.

9. Esc key - Return the vi editor to the command mode

10. “ / “ - Helps to search for a particular string within the file. The

string along with the followed by the “/” is to be entered


on the status line.

11. “?” - Works the same way as “/” key.

12. In the command mode

- h – left move

- l – right move

- k – up

- j – down

13. w – Moves forward by a word. Assumes that punctuations are next words.

14. W – Moves forward by a word and this identifies punctuations as a part of the

word.

15. e – Takes us to the last character of the word

16. E – Takes us to the last character of the word and ignores any punctuations

17. b – Moves backward by a word

18. B – Backward by a word and ignores any punctuation.

19. ^ - Takes us to the beginning of the line.

20. $ - Takes us to the end of the line.

21. L – Takes us to the last line of the file.

22. G – Works like the GOTO command. For, example, to goto the second line in

the file we can say 2G.

Screen Commands

1. Ctrl F – Moves forward by a screen. To have continuing the last two lines of the
previous screen are displayed.
2. Ctrl B – Moves backward by a screen. Here again two lines of the previous screen
are displayed.
3. Ctrl D – Moves the cursor half the screen forward.
4. Ctrl U – Moves the cursor half the screen backward.
5. Ctrl L – To clear any message that vi has displayed or to clear any system messages
that appear on the screen.
6. Ctrl G – Displays the status on the status line. Give us the name of the file we are
editing, the number of line in the file, the current line number and the percentage of
the file (in lines) that precedes the cursor.

Editing Commands

Text Insertion In Vi

In order to insert a text within the file, first we must type in “i” to make sure that we are
in the insert moode.

The following commands perform the insertion function

1. i / I – Invokes insertion mode. Text insertion possible only after we invoke the insert
mode. The capital I invokes the insert mode and insertion takes place at the beginning.
2. O – Allows insertion by creating a blank line above the current line.
3. o – Allows insertion by creating a blank line above the current line.
4. a – Used for appending the text. Text is appended after the cursor position.
5. A – Used for appending the text. Text is appended at the end of the line.

Deleting Data in vi

Suppose we want to delete a character or a word or a line that we have typed, then we go in
for the delete commands.

1. dd – Deletes the line in which the cursor is positioned.


2. dw – Deletes the word from the cursor position to the end of the word. It ignores any
punctuation that appear with the word.
3. x – Deletes the character at the cursor position.
4. X – Deletes the character before the cursor position.
5. D – Deletes the line from the current cursor position to the end of the line.
The Undo Command

To use undo command, we must first ensure that we are in the command mode and
then press “u”.

Joining Lines of Text

To join two lines, place the cursor at the end of the first line and then give the command
“J”.

Line Numbering of Text

1. To put line number – (Esc):set number


2. If we don’t want the numbering to be done – (Esc):set no number

Copy, Delete and Move multiple lines

Example

1. To copy the second line in our file below the fifth line then use “:2co5”
2. To copy the first three lines below the seventh line of our file, then use “:1,3co7”
3. To move the third line of the file to the ninth line of the file then “:3mo9”
4. To move the fourth line to the seventh line of a file to the end of the file then use
“:4,7mo$”
5. To delete from the fifth line to the seventh line in a file, then use “:5,7d”
6. To delete the fourth line from the current position, then use “: .+4d”
7. To delete the fifth line above the current cursor position, then “: .-5d”

Quit From Vi Editor

1. :q! – Quit without writing the changes into the disk file.
2. :wq! – Quit after writing the changes into the disk file.
3. :x – Replaces the old copy of the file with the new one and then quits.
4. ZZ – Makes changes and quits from the command mode
Ex. No : 5

Date :

Pipes

Aim

To study and execute the operation of the pipe command.

Procedure

A pipe is a mechanism which takes the output of a command before the pipe symbol as
the input for the next command after the pipe symbol.

Command : pipe (|)

Function : To execute multiple processes from a single

command line

Syntax : $command1 | command2

Example1 : $who | wc –l

Here the output of the command “who” is taken as the input for
the command and the result of that will be displayed.

Example2 : $cat a1 | head -3

The output of this command will be the display of

the first three lines of the file a1.


Example3 : $cat sh1 sh2 | pr

The above command will concatenate the two files

‘sh1’ and ‘sh2’ and use the standard output as the

input of the ‘pr’ command.


Ex. No : 6

Date :

Simple Filters

Aim

To study and execute the operations of the filter commands

Procedure

1. A filter takes input from the standard input processes it and then sends the output
the standard output. Filters also take input from a file.
2. Filters also used to store the intermediate results of a long pipe.
3. We can extract specific columns of a file and can merge two or more files together
using filters.

The head command

Command : head

Function : To display the top portion of a file. By default, the

command displays the first ten line of the file.

Syntax : $head [options] [filename]

Examples : $head bs - To display the first 10 lines of the file bs.

$head -4 bs - To display the first 4 lines of the file bs.

The tail command

Command : tail
Function : To display the bottom portion of a file. By default, the

command displays the last ten lines of the file.

Syntax : $tail [options] [filename]

Examples : $tail bs - To display the last 10 lines of the file bs.

$tail -10c bs - To display the last 10 characters from the

file named bs.

The sort command

Command : sort

Function : To arrange the input taken from the standard input in

alphabetical order.

Syntax : $sort [option] [filename]

Example : $sort bs- To sort the file in alphabetical order.

$sort –r bs - To sorts the input taken from the keyboard

in the reverse order.

$sort –o b a - Sorts the content of the file a and stores the

output in the file b.


Options used with sort command

S.No. Options Purpose


1 -m{merge) Merge the input files, without sorting them
Ignores the difference between uppercase and lower characters in the
2 -f
sorting comparison.
3 -n(for numeric) Sort on numeric values
4 +pos Skips given number of fields to start sort key
5 -pos To stop the comparison just before the given field number
‘c’ is the field delimiter, sort according to the filed separated, specified as
6 -tc
a character in c.
7 -u Ignore duplicate lines before sorting
8 -A Sort according to ACII collating sequence.
9 -b Ignore leading blanks and tabs before sorting.
10 -d Sorts according to dictionary order (Only spaces digits and letters)
11 -I Ignore non-printable ASCII characters before sorting

The pr command

Command : pr

Function : Converts the text files for printing.

Syntax : $pr [filename]

Example : $pr bs

The cut command

Command : cut

Function : To remove sections from each line of file.

Syntax : $cut [option] [filename]

Examples : $cut –c 1 bs - Cuts the first character from each


line of the specified file.

$cut –c 1,5 bs - Cuts the first and the 5th characters of

each line in the specified file.

$cut –c 1-4 bs - Cuts the from first to fifth characters of

each line in the specified file.

$cut –d “” –f1 bs - To display the selected fields from

the file named bs

$cut –d “a” –f2 bs - To display all characters from each

line of the character ‘a’ in the

second field

$cut –d “a” –s –f2 bs - To suppress lines that does not

contain the character ‘a’

The Paste command

Command : paste

Function : To paste line from one or more files vertically and displays

the result in the standard output.

Syntax : $paste [options] [file name]

Examples : $paste e1 e2 – Concatenate the files of e1 and e2.

$paste –d% e1 e2 – The default field separator

tab character as been charged

to the % character when

concatenating lines from the

two files e1 & e2.

$paste –s e1 e2 – To merge subsequent lines


from two files and combining

them into a long line.

S.No. Options Purpose


Specifies a single character or a group of characters as char(s) for delimiting the
1 -d char (s)
columns. The tab character is used as the default delimiter.
Merger subsequent lines from one fie separated by the default delimiter and
2 -s
combining them into one long line.

The join command

Command : join

Function : Used to extract common lines from two sorted files,

provided there should be a common filed. The join

command concatenates the line from each input file column

by column (By displaying the common field only once)

with a space in between them.

Syntax : $join [option] [filename1] [filename2]

Examples : $join e1 e2 - Joins the common lines of the two

files depending upon the names in

both files e1 and e2.

$join –v 1 e1 e2 - Uncommon lines of the 1st

file will be displayed.

The uniq command

Command : uniq

Function : To eliminate the duplicate adjacent lines in a file.


Syntax : $uniq [options] [file name]

Examples : $uniq bs – Removes the adjacent duplicate lines

from the file bs and displays the

output.

$uniq –c bs - To display the count of repeated

lines in the file name bs

$uniq –u bs - To display only uniq lines, without

displaying repeated lines.

$uniq –d bs - Display only repeated lines without

unique lines.

The nl command

Command : nl

Function : Used to add the line numbers to a file. The line number will

be displayed on the left side of each line.

Syntax : $nl [options] [file name]

Examples : $nl bs – Numbers the lines of the file bs.

$nl –w3 bs - The space between the number and

the content will be increased by 3 tab

spaces

$nl –s ‘##’ bs - Used to separate the line numbering

and the corresponding lines using the

‘##’ character.

$nl –i 3 bs - Numbering will start from 1 and

continues by the difference 3.


$nl –v 40 bs - Numbering will start from 40 and

continues by the difference 1.

The tr command

Command : tr

Function : Translate the characters taken from the standard input.

Examples : $ cat > a1

welcome to c language

$ cat a1

welcome to c language

$ cat a1 | tr "[a-z]" "[A-Z]"

WELCOME TO C LANGUAGE
The more command

Command : more

Function : Displays the output of a command page by page.

Syntax : $more [options] [file name]

Examples : $who | more - Will give the list of people logged in

one screen at a time.

$more a1.txt - To view the contents of the file a1.txt

$more +16 a1.txt - To display the content of the

file a1.txt from the 16th line

$more +/24 a1.txt - To search for a pattern in the

file a1.txt

The cmp command

Command : cmp

Function : Compares any two files including binary files. It takes file

names as arguments

Syntax : $cmp [options] [filename1] [filename2]

Examples : $cmp a1.txt a2.txt – It displays the character

position and the line number

of the first mismatch between

the files and returns the ‘$’

prompt.

The diff command


Command : diff

Function : Produces the complete index of all lines that differ between

two files, along with their line numbers.

Syntax : $diff [options] [filename1] [filename2]

Examples : $diff a1.txt a2.txt

The comm. command

Command : comm

Function : Compares and displays lines common as well as unique to

two files. The files must be in sorted order.

Syntax : $comm [options] [filename1] [filename2]

Examples : $comm -12 a1.txt a2.txt - Displays only the common

lines of the two files specified.

$comm a1.txt a2.txt – High lights the common lines

of the two files specified in the


command.

$comm -2 a1.txt a2.txt - Displays the content of the 1st

file, highlights the common


lines of the two files and does
not display the uncommon lines
of the 2nd file.

$comm -1 a1.txt a2.txt -Displays the content of the

2nd file, highlights the

common lines of the two files

and does not display the


uncommon lines of the 1st file
Ex. No : 7

Date :

Command Line Parameters With Simple UNIX Commands.


Aim

To study and execute the command line parameters with simple UNIX commands.

Procedure

1. As in case of C and perl programs information can be conveyed to a shell program in


the form of command line arguments.
2. With the shell script these command line arguments are called as positional
parameters.
3. The first argument is passed on as parameter no.1, second argument is passed on as
parameter no.2 and so on.
4. There are nine such variables to capture and hold values given in a command line.
These are $1, $2, …… $9.
5. The $1 variable holds the first argument, the $2 holds the second argument and so
on.
6. Depending upon their physical positions in the command line they are called
positional parameters.

Special Shell parameters

Shell Parameters Description


$1, $2 Positional parameters
$# The number of positional parameters
$* The list of positional parameters
$@ Same as $*, Except when enclosed in double quotes
$$ The process number of the current shell
$! The process number of the last background command
$0 The name of the command being executed
$? The exit status of the last executed command

Examples
$ a1.sh Ravi Ram Kavitha Parveen

$ echo $0 # Name of the command executed

a1.sh

$ echo $1 $2 $3 $4 # Positional parameters

Ravi Ram Kavitha Parveen

$ echo $# # Number of arguments

$echo $* #List of arguments

Ravi Ram Kavitha Parveen

$-

The exit status of a command

1. The exit command helps in terminating the shell script and tell us the exit status of
the script.
2. If the script was executed successfully before exiting, the exit command returns a
“0” else it return “1”.

Examples

$ mkdir lab1

$ echo $?

$ rmdir lab2

rmdir: `lab2': No such file or directory

$ echo $?

$-
The set command: Assigning values to positional parameters

Values to positional parameters can be assigned using the set command.

Example

$ set A B C D E F

$ echo $1 $3 $6

ACF

$-

Positional parameters and Excess Arguments

1. In certain situations one may give more than nine arguments in a command line.
2. This results in excess values to be assigned to the nine positional parameters.

Examples

$ set A B C D E F G H I J K

$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11

A B C D E F G H I A0 A1

$-

The above situations are handled using the shift command


The shift command handling

Command : shift

Function : It shifts out the values assigned to the positional parameters

to the left by an integer value mentioned with the shift

statement as its arguments

Syntax : $shift n

Examples

$ set A B C D E F G H I J K

$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11

A B C D E F G H I A0 A1

$ shift 5

$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11

F G H I J K F0 F1

$-

When used without any argument the shift command shifts the contents of the
positional parameters by just one position to the left.

Handling excess command line arguments without using shift command.

In the argument number consists of more that nine, enlose it within the flower braces.

Example

$ set A B C D E F G H I J K
$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11}

ABCDEFGHIJK

$-
Ex. No : 8

Date :

Shell Programming Fundamentals


A. Shell Variables

Aim

To study, create, assigning values and accessing the shell variables.

Rules for constructing variable names

1. The first character in the variable name must to an alphabet and can be followed by
any number of alphabets or digits or underscores.
2. No special character are allowed within a variable name except an underscore.
3. The variables should not be a keyword.
4. No commas or blank spaces are allowed within a variable name.
5. Variable names are case sensitive
6. A variable name should not be of length more than 20 characters.

Creating shell variables

$ set <variable name> - To create a scalar variable

Example

$ set b

$set <Variable>=<value> - To initialize a shell variable with a

Value

Example

$set b=10
Assigning Values to the shell variables and Accessing shell variables’ value

Assigning Values to the shell variables

$ b=15

$ c=5.4

$ d=abcd

$ a="Welcome to shell programming"

Accessing shell variables’ value

$ echo The value of a is $a ans b is $b

The value of a is Welcome to shell programming ans b is 15

$-

Example

$ a=Ravi;b=Kumar

$ c=$a$b

$ echo $c

RaviKumar

$-

Local and global variables


1. By default the shell variables are ‘local’ to the shell that create them.
2. The values of these shell variables are not available to the newly created child process.
3. The export command is provided by UNIX, which can be used to declare a variable as
global so that these variables are available to the child process.

Program for local variable

$ city=chennai

$ echo "${city}"

chennai

$ sh //Creates a new shell

$ echo "${city}" //No response

sh-3.00$ city=Bangalore//Assigning a new value ‘bangalore’ city

sh-3.00$ echo "${city}"

Bangalore

sh-3.00$ exit

ctrl + d //Returns to parent shell

$ echo "${city}" //Returns ‘Chennai’. Parent is unaware of

‘bangalore’

chennai

$ sh //Creates a child shell

sh-3.00$ echo "${city}" //Value ‘Bangalore’ destroyed

sh-3.00$ exit

Ctrl + d //Return to the parent

$-
Program for global variable

$ city=chennai

$ export city

$ echo "${city}"

chennai

$ sh //Creates a new child shell

sh-3.00$ echo "${city}" //Child shell has the variable city

chennai

sh-3.00$ city=Bangalore //Assigning a new value ‘bangalore’ city

sh-3.00$ echo "${city}"

Bangalore

Ctrl + d //Return to parent

sh-3.00$ exit

$ echo "${city}" //Parent shell retains its original value ‘chennai’

chennai

$ sh

sh-3.00$ echo "${city}"

chennai

sh-3.00$

The last two commands display that the variables can be exported or passed to sub
shells, but the reverse is not true.
Unsetting Variables: The unset command

The unset command is used for unsetting variables.

$unset <variable name>

Example

$ z=hello - Assigns the variable with the value “hello”

$ echo $z - Displays the value of z

Hello

$ unset z - Unsets the variable z

$ echo $z - Since the variable z is unset, it displays a blank line.

$-
B. Conditional Statements

Aim

To write a shell program to find out the biggest number using the conditional
statements.

Algorithm

1. Get two numbers as input using the read command


2. Compare the two numbers using the ‘if ‘ conditional statement.
3. Display the biggest number.

Program

echo "Enter the two numbers"

read a

read b

if test $a -gt $b

then

echo "A is Big"

else

echo "B is Big"

fi

Output
[user2@jayam ~]$ sh big.sh

Enter the two numbers

A is Big

[user2@jayam ~]$
C. Testing and Loops

Testing

Aim

To write a shell program to find the mode of a given file using the test command.

Algorithm

1. Start the vi editor and create a file.


2. Read the file name
3. If it is ! –e $filename, ! –r $filename, ! –w $filename the file does not exist, not
readable and not writable respectively.
4. Else the file is both readable and writable.
5. Display the output

Program

echo "Enter The file name"

read f

if [ ! -e $f ]

then

echo "File doesnot Exist"

elif [ ! -r $f ]

then

echo "File is not readable"

elif [ ! -w $f ]
then

echo "File is not writable"

else

echo "File is both readable and writable"

fi

Output

[user2@jayam ~]$ sh test.sh

Enter The file name

test.sh

File is both readable and writable

[user2@jayam ~]$ sh test.sh

Enter The file name

ex1

File doesnot Exist

[user2@jayam ~]$ sh test.sh

Enter The file name

File doesnot Exist

[user2@jayam ~]$

For Loop

Aim
To write a shell program to calculate the sum of the 5 numbers using simple for loop.

Algorithm

1. Start the vi editor and create a file.


2. Declare a variable named as ‘sum’ and initialize it to zero.
3. Get the input of 5 numbers using for loop
4. Calculate the sum of the input numbers and store that value in the variable sum.
5. Display the output

Program

sum=0

for i in 1 2 3 4 5

do

sum=`expr $sum + $i`

done

echo "Sum of the first five number is $sum"

Output

"for1.sh" 7L, 99C written

[user2@jayam ~]$ sh for1.sh

Sum of the first five number is 15

[user2@jayam ~]$
While Loop

Aim

To calculate the factorial value of the given number using while loop

Algorithm

1. Start the vi editor and create a file.


2. Get the input using the variable n, and the read command.
3. Calculate the factorial of the given input using while loop.
4. Store the result in the variable ‘f’
5. Display the output

Program

echo Enter a number

read n

i=1

f=1

while [ $i -le $n ]

do

f=`expr $f \* $i`

i=`expr $i + 1`

done

echo "factorial is $f"

Output
"fact1.sh" [New] 11L, 121C written

[user2@jayam ~]$ sh fact1.sh

Enter a number

factorial is 120

[user2@jayam ~]$ sh fact1.sh

Enter a number

factorial is 24

[user2@jayam ~]$ sh fact1.sh

Enter a number

factorial is 5040

[user2@jayam ~]$
D. Simple shell Program

Program1

Aim

To write a simple shell program to compare two strings

Algorithm

1. Start the vi editor and create a file.


2. Get the two strings as input in the command line itself.
3. Compare those two strings using the variable numbers.
4. If the strings are equal the display “Strings are equal”, else display “Strings are not
equal”.
5. Display the output

Program

if [ $1 = $2 ]

then

echo "strings are equal"

else

echo "strings are not equal"

fi

Output
"simple.sh" [New] 7L, 83C written

[user2@jayam ~]$ sh simple.sh shell shell

strings are equal

[user2@jayam ~]$ sh simple.sh welcome shell

strings are not equal

[user2@jayam ~]$
Program2

Aim

To write a simple shell program to calculate the sum of the numbers within a given
upper limit.

Algorithm

1. Start the vi editor and create a file.


2. Get the upper limit value to calculate the sum.
3. Initialize the variables ‘i’ as 2 and ‘sum’ as 0.
4. Calculate the sum of the numbers from 2 to the given upper limit with the
increment value as 2.
5. Store the output in the variable ‘sum’.
6. Display the output

Program

echo "Enter upper limit"

read n

i=2

sum=0

while test $i -lt $n

do

sum=`expr $sum + $i`

i=`expr $i + 2`

done

echo "sum is: $sum"


Output

"upper.sh" [New] 12L, 130C written

[user2@jayam ~]$ sh upper.sh

Enter upper limit

sum is: 6

[user2@jayam ~]$ sh upper.sh

Enter upper limit

sum is: 12

[user2@jayam ~]$ sh upper.sh

Enter upper limit

10

sum is: 20

[user2@jayam ~]$
E. Grep and Sed commands

Grep Command

Aim

To write a simple shell program to manipulate the grep command

Algorithm

1. Start the vi editor and create a file.


2. Get the directory name as the input
3. List of files in the given directory will be displayed.
4. Give one of the filenames as the input to perform the grep operation
5. If the given input matches with the filenames available in the given directory then
the pattern matching is done and the file name will be displayed as the output.

Program

echo "Enter the directory name"

read name

echo "The list of files in the directory $name are"

ls $name

echo "Grep Operation"

echo "Enter the file name"

read file

grep "Pass" $file

Output
"grep.sh" 9L, 181C written

[user2@jayam ~]$ sh grep.sh

Enter the directory name

The list of files in the directory A are

Grep Operation

Enter the file name

[user2@jayam ~]$
Sed command

Aim

To write a shell program for replacing the string using grep.

Algorithm

1. Read the input file.


2. If the input file compared with e, if the file contains e.
3. The first letter of e must be changed to XX using end command.
4. Then display the file.

Syntax

sed ’[edit commands]’ filename

Output

$ Enter the input file: wel.txt

file updated.

& cat wel.txt


F.AWK filter

Aim

To study and execute the functions of AWK filter.

Description

The awk programming language is a scripting language that can be used for very simple
single-line applications to large applications. awk is a general-purpose language, but it excels at
its original task of text processing. Its same as SED but has more powerful features . We can
perform arithmetic operations and many kind of analysis of the data in our file through
command line .

Structure

awk ' BEGIN {}

pattern { actions }

...

END {} ' <filenames>

The structure of an awk program can be split into three sections. The BEGIN section is
performed before the first line is read from the input file(s), and the END section is performed
after the last line is processed from the input file(s). Between the optional BEGIN and END
sections is the awk pattern/action section. For each input file specified, each of the patterns is
compared in order, and if a pattern matches, then its associated action is performed.

Consider a file missilie.txt:


Thor:65:109330:1725:10250

Snark:67:48147:6325:650

Jupiter:55:110000:1976:9022

Atlas:75:260000:6300:17500

Titan:98:221500:6300:15000

Minuteman III:56:65000:6300:15000

Peacekeeper:71:195000:6000:15000

We can emit lines in much the same way that sed did, but include a search expression as
the pattern and the print command as the action:

(Command Line)

# awk '/Thor/{print}' missiles.txt

Thor:65:109330:1725:10250

without a pattern, We can simply emit the entire file:

# awk '{print}' missiles.txt

Thor:65:109330:1725:10250

Snark:67:48147:6325:650

Jupiter:55:110000:1976:9022

Atlas:75:260000:6300:17500

Titan:98:221500:6300:15000

Minuteman III:56:65000:6300:15000
Peacekeeper:71:195000:6000:15000

Arithmetic expressions are also possible on the data. The following example, emits
those missiles that have a range of 12,000 miles or more:

# awk -F: '$5 > 12000 { print $1 }' missiles.txt

Atlas

Titan

Minuteman III

Peacekeeper

awk’s Built-In Variables

Variable Description

NR Input record number

NF Number of fields in the current record

FS Field separator (default space and tab)

OFS Output field separator (default space)

RS Input record separator (default newline)

ORS Output record separator (default newline)

FILENAME Current input filename

We can also use if for and While statements in the awk script.
G. Security Commands

Basics

Users

root: super user (uid = 0)

daemon: handle networks.

nobody: owns no files, used as a default user for unprivileged operations.

User needs to log in with a password. The encrypted password is stored in

/etc/shadow.

User information is stored in /etc/passwd, the place that was used to store

passwords (not any more). The following is an example of an entry in this

file.

john:x:30000:40000:John Doe:/home/john:/usr/local

/bin/tcsh

A few useful commands

% /bin/su xyz (Change your user ID to xyz, su means “substitute

user”)

% /bin/su - (Change to root. This is a common way to invoke

Superusr access). Once you are in the superuser account, the prompt

becomes the pound sign (#).

% whoami (to print out your current user name)

% /usr/bin/id (display both uid and gid)

Groups

Why do we need groups?


Assign permission based on groups.

A user has a primary group (listed in /etc/passwd), and this is the one

associated to the files the user created.

Any user can be a member of multiple groups.

Group member information is stored in /etc/group

NIS: % ypcat group (can display all the groups and their members)

% groups uid (display the groups that uid belongs to)

File Permissions

The meaning of the permission bits in Unix.

Owner (u), Group (g), and Others (o).

Readable (r), Writable (w), and Executable (x).

Example: -rwxrwxrwx (777)

Permissions on Directories:

r: the directory can be listed.

x: the directory can be entered.

w: can create/delete a file or a directory within the directory.

What is the most secure setting for your web directories? Why?

“rwxr-xr-x” allows remote users to view the contents of your web

directory.

You can change it to “rwx--x--x”.

Change permission: chmod

% chmod -R a+rx directory


u: owner

g: group

o: others

a: all

Full Access Control List

% getfacl

% setfacl

Default File Permission

Q: What is the default file permission assigned to the newly created files?

This default permission is stored in the umask environment variable.

umask: permissions you do not want

Default value in some systems: 022

This set the permission of new files (non-executable) to rw-r--r—.

Safest value: 077

This sets the permission of new files (non-executable) to rw-------.

Check your own setting

% umask

Change the umask value

% umask 077

Put this command into your .cshrc file.

Change the owner of files


The chown command.

% chown wedu file

Q: Can we allow a user to change the owner of files to another user?

No. Actually, only root can use chown. Why?

Disk quota problem.

Set-UID problem.

Change the group of files

The chgrp command.

% chgrp seed /home/seed/785

Can we allow a user to change the group of files to another group?

Yes/No. If you want to change to group XYZ, you must be a member

of XYZ

The reason is similar to the chown command (Set-GID).

Find manuals for Unix commands

umask(2), umask(1)

% man -s 2 umask

% man -s 1 umask


Ex.No:9

Date:

UNIX C

A. Simple C programs to simulate the basic UNIX commands (Fork, Signal)

Fork System Call

Aim

To write a C program to simulate fork system call.

Algorithm

1. Using fork system call, create a new process.


2. Assign the process id in the variable ‘pid’.
3. If pid is equal to -1, then report an error and terminate using the exit system call.
4. Otherwise, it is the parent process.
5. Print the ids of both child and parent process.

Program

#include<stdio.h>

main()

int child;

if( (child=fork() )==0 )

{
printf("Child pid %d \n",getpid());

pause();

printf("Child pid %d \n",child);

exit(child);

Output

"a1.c" 13L, 161C written

[user2@jayam ~]$ cc a1.c

[user2@jayam ~]$ ./a.out a1.c

Child pid 6877

Child pid 6877

[user2@jayam ~]$

Signal System call

Aim

To write a C program to simulate signal system call.

Algorithm
1. Start the vi editor and create a file.
2. Get the parent process group using the setpgrp() system call.
3. Invoke all the child process available in the given parent process group using fork()
system call.
4. Get and display the pid of all the child process until getting the pid of the last child
process.
5. After getting all the pids of all the child process, kill the process using the
kill(0,SIGINT) command.

Program

#include<signal.h>

main()

register int i;

int j=0;

setpgrp();

printf("Parent process group = %d \n\n",getpgrp());

printf("child process \n");

for(i=0;i<=10;i++)

if(fork()==0)

if((i%2)==0)

setpgrp();

printf("%d child pid %d pgrp=%d\n",i,getpid(),getpgrp());

pause();

}
kill(0,SIGINT);

Output

"signal.c" [New] 21L, 295C written

[user2@jayam ~]$ cc signal.c

[user2@jayam ~]$ ./a.out

Parent process group = 6952

child process

0 child pid 6953 pgrp=6953

1 child pid 6954 pgrp=6952

2 child pid 6955 pgrp=6955

3 child pid 6956 pgrp=6952

4 child pid 6957 pgrp=6957

5 child pid 6958 pgrp=6952

6 child pid 6959 pgrp=6959

7 child pid 6960 pgrp=6952

8 child pid 6961 pgrp=6961

9 child pid 6962 pgrp=6952

10 child pid 6963 pgrp=6963

[user2@jayam ~]$
B. File Handling

Aim

To write a C program to copy the content of the one file to the another file in UNIX
environment.

Algorithm

1. Start the vi editor and create a file.


2. Open the two files to copy the content form one to another.
3. If the number of arguments passed to the program is less than 3, then show the
error message.
4. Otherwise copy the content of the first file to the second file given in the execution
command line.
5. Display the content of the second file using ‘cat’ command.

Program

#include<stdio.h>

int main(int argc, char *argv[])

int fd1,fd2,n;

char buf[512];

if(argc<3)

printf("Error in the number of arguments");

exit(1);

}
if((fd1=open(argv[1],0))<0)

printf("Can't open %s",argv[1]);

exit(1);

if((fd2=creat(argv[2],0644))<0)

printf("Can't create %s",argv[2]);

exit(1);

n=read(fd1,buf,512);

write(fd2,buf,n);

close(fd1);

close(fd2);

}
Output

"filehand.c" [New] 26L, 371C written

[user2@jayam ~]$ cc filehand.c

[user2@jayam ~]$ ./a.out signal.c s1

[user2@jayam ~]$ cat s1

#include<signal.h>

main()

register int i;

int j=0;

setpgrp();

printf("Parent process group = %d \n\n",getpgrp());

printf("child process \n");

for(i=0;i<=10;i++)

if(fork()==0)

if((i%2)==0)

setpgrp();

printf("%d child pid %d pgrp=%d\n",i,getpid(),getpgrp());

pause();

kill(0,SIGINT);
}

[user2@jayam ~]$
Content Beyond the Syllabus

Ex. No:1

Date :

Fibonacci Series

Aim

To write a shell program to find the Fibonacci series of a given range.

Algorithm

1. Start the vi editor and create a file.


2. Give the range to find out the Fibonacci series.
3. Calculate the Fibonacci series using do – while loop.
4. Store the each calculated value in the variables ‘a’ and ‘b’.
5. Display the result.

Program

echo "program to generate fibonacci series"

echo "enter the range to be displayed"

read n

a=0

b=1

echo fibo series

echo $a

echo $b
i=2

while test $i -lt $n

do

c=`expr $a + $b`

echo $c

i=`expr $i + 1`

a=$b

b=$c

done

Output

"fib.sh" [New] 18L, 216C written

[user2@jayam ~]$ sh fib.sh

program to generate fibonacci series

enter the range to be displayed

fibo series

[user2@jayam ~]$ sh fib.sh

program to generate fibonacci series

enter the range to be displayed


8

fibo series

13

[user2@jayam ~]$
Ex. No:2

Date :

Reverse a Given Number

Aim

To write a C program to reverse a given number.

Algorithm

1. Start the vi editor and create a file.


2. Get number to be reversed.
3. Using while loop perform the operations to reverse the given input.
4. Display the result.

Program

#include<stdio.h>

main()

int n,a,r=0;

printf("enter any no to get its reverse: ");

scanf("%d",&n);

while(n>=1)

a=n%10;

r=r*10+a;

n=n/10;
}

printf("reverse=%d",r);

Output

"rev.c" [New] 16L, 171C written

[user2@jayam ~]$ cc rev.c

[user2@jayam ~]$ ./a.out

enter any no to get its reverse: 123

reverse=321

[user2@jayam ~]$
Ex. No:3

Date :

Displaying the Matrices

Aim

To write a C program to display two matrices.

Algorithm

1. Start the vi editor and create a file.


2. Declare two 3 X 2 matrices using two dimensional array.
3. Get the input for each matrix using for loop.
4. Using for loop display the two 3 X 2 matrices with values.

Program

#include<stdio.h>
main()
{
int a[3][2],b[3][2],i,j;
printf("enter value for a matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("enter value for b matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf("%d",&b[i][j]);
}
printf("\na matrix is\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(" %d ",a[i][j]);
}
printf("\n");
}

printf("\nb matrix is\n\n");


for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf(" %d ",b[i][j]);
}
printf("\n");
}
}

Output

"mat.c" [New] 38L, 471C written

[user2@jayam ~]$ cc mat.c

[user2@jayam ~]$ ./a.out

enter value for a matrix:

enter value for b matrix:


8

a matrix is

3 2

5 1

6 3

b matrix is

8 9

4 5

6 1

[user2@jayam ~]$
JAYARAM
COLLEGE OF ENGINEERING AND
TECHNOLOGY

Estd: 1994
Pagalavadi, Tiruchirappalli - 621014

(Approved by AICTE and Affiliated to Anna


University)
ISO 9001:2000 Certified
(Accredited by NBA, New Delhi)

Department of CSE

Academic Year 2009 – 2010 (Even Semester)

CS1151 - COMPUTER PRACTICE

LABORATORY II

MANUAL

You might also like