0% found this document useful (0 votes)
92 views173 pages

OS Lab by Raushan Sir

The document discusses various Linux commands like cal, date, mkdir, pwd, touch, cat, ls, cp, mv, rm, echo, wc, grep, head, tail, history, less, man, top, sort, cut, sed, df, du and shell scripting. It provides details on the usage and applications of these commands.

Uploaded by

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

OS Lab by Raushan Sir

The document discusses various Linux commands like cal, date, mkdir, pwd, touch, cat, ls, cp, mv, rm, echo, wc, grep, head, tail, history, less, man, top, sort, cut, sed, df, du and shell scripting. It provides details on the usage and applications of these commands.

Uploaded by

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

OS Lab

Linux Commands, Shell Programming


and System Calls

Class Presentations on OS Lab

by Raushan Kumar Singh


Linux Commands
1) cal
By default, the cal command shows the current month calendar as
output.

cal [ [ month ] year]


cal
cal 08 2000
cal 2018
cal -3
The rectangular bracket means it is optional, so if used without an
option, it will display a calendar of the current month and year.
2)date
date command is used to display the system date and
time.
$date
$date +%[format-option]
$date "+%D"
$date "+%D %T"
$date "+%Y-%m-%d"
$date "+%Y/%m/%d"
Directory
 Unix uses a hierarchical structure for organizing files and directories.
This structure is often referred to as a directory tree. The tree has a
single root node, the slash character (/), and all other directories are
contained below it.
 $mkdir dirname
 $mkdir docs pub
 $rmdir dirname
 $cd dirname
 $cd /usr/local/bin
 To quickly return to your home directory, use the ~ (tilde) character
as the directory name.
 cd ~
 cd .. change to parent directory
pwd

Nice and simple, the pwd command prints the working


directory (the current directory) from the root /
directory.
4) touch
It is used to create a file without any content. The file
created using touch command is empty. This command
can be used when the user doesn’t have data to store at
the time of file creation.

touch file_name
3)cat
 Cat(concatenate) command is very frequently used in
Linux. It reads data from the file and gives their content as
output. It helps us to create, view, concatenate files.
 $cat filename
 $cat file1 file2
 $cat -n filename
 $ cat > newfile
 ………
 Ctrl+D to save the file
 $cat [filename-whose-contents-is-to-be-copied] >
[destination-filename]
Cont..
Cat command can append the contents of one file to
the end of another file.
$cat file1 >> file2

Cat command to write in an already existing file.

$cat >> hello.txt


….
Ctrl+D
5) ls
Listing Directories and Files: All data in Unix is
organized into files. All files are organized into
directories. These directories are organized into a tree-
like structure called the filesystem.
ls
ls -l
ls ch*.doc
ls -a
cp
Copying Files
$ cp filename copyfile
mv
To change the name of a file, use the mv command.

 mv filename newfile
rm command
To delete an existing file, use the rm command.
$ rm filename
echo
The echo command prints (echoes) a string of text to
the terminal window.

The command below will print the words “A string of


text” on the terminal window.

echo A string of text


6) wc
You can use the wc command to get a count of the
total number of lines, words, and characters contained
in a file.
wc filename
grep
 The grep searches a file for a particular pattern of characters,
and displays all lines that contain that pattern.
 grep train abc.txt
 Case insensitive search :
 $grep -i "UNix" geekfile.txt
 Displaying the count of number of matches :
 $grep -c "unix" geekfile.txt
 Show line number while displaying the output
 $ grep -n "unix" geekfile.txt
 Inverting the pattern match : You can display the lines
that are not matched with the specified search string
pattern using the -v option.
 $ grep -v "unix" geekfile.txt
head
The head command gives you a listing of the first 10
lines of a file. If you want to see fewer or more lines,
use the -n (number) option.
head core.c

head -n 5 core.c
tail

The tail command gives you a listing of the last 10


lines of a file. If you want to see fewer or more lines,
use the -n (number) option. In this example, we use tail
with its default of 10 lines. We then repeat the
command asking for only five lines.

tail core.c

tail -n 5 core.c
history
The history command lists the commands you have
previously issued on the command line.
less
The less command allows you to view files without
opening an editor.
With less you can scroll forward and backward
through the file using the Up and Down Arrow keys,
the PgUp and PgDn keys and the Home and End keys.
Press the Q key to quit from less.

less hello.txt
man
The man command displays the “man pages” for a
command in less . The man pages are the user manual
for that command.
top

The top command shows you a real-time display of the


data relating to your Linux machine.
SORT
 SORT command is used to sort a file, arranging the records in a particular
order.
 cat > file.txt $ sort file.txt
Output :
abhishek
abhishek
chitransh
chitransh
satish divyam
rajan harsh
naveen naveen
divyam rajan
harsh satish
2. -r Option: Sorting In Reverse Order: You can
perform a reverse-order sort using the -r flag.
$ sort -r inputfile.txt
-n Option: To sort a file numerically used –n option.
This option is used to sort the file with numeric data
present inside.

sort -n filename.txt
sort -nr filename.txt
 -k Option: Unix provides the feature of sorting a table on the basis of
any column number by using -k option.
$ cat > employee.txt
manager 5000
clerk 4000
employee 6000
peon 4500
director 9000
guard 3000
$ sort -k 2n employee.txt
guard 3000
clerk 4000
peon 4500
manager 5000
employee 6000
director 9000
cut command
cut command slices a line and extracts the text. It is
necessary to specify option with command otherwise it
gives error.
cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Without any option specified it displays error.
$ cut state.txt
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.
 1. -b(byte): To extract the specific bytes, you need to follow -b option
with the list of byte numbers separated by comma. Range of bytes can
also be specified using the hyphen(-). Tabs and backspaces are treated
like as a character of 1 byte.
 List without ranges
$ cut -b 1,2,3 state.txt
And
Aru
Ass
Bih
Chh
 List with ranges
 $ cut -b 1-3,5-7 state.txt
Andra
Aruach
Assm
Bihr
Chhtti
 It uses a special form for selecting bytes from beginning upto the end
of the line:
 In this, 1- indicate from 1st byte to end byte of a line
 $ cut -b 1- state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
 In this, -3 indicate from 1st byte to 3rd byte of a line
 $ cut -b -3 state.txt
And
Aru
Ass
Bih
Chh
-f (field):
 $cut -d "delimiter" -f (field number) file.txt
 $ cut -d " " -f 1 state.txt
Andhra
Arunachal
Assam
Bihar
Chhattisgarh
 $ cut -d " " -f 1-4 state.txt
Output:
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Applications of cut Command
$ cat state.txt | cut -d ' ' -f 1 | sort -r
Chhattisgarh
Bihar
Assam
Arunachal
Andhra
$ cat state.txt | head -n 3 | cut -d ' ' -f 1 > list.txt

$ cat list.txt
Andhra
Arunachal
Assam
SED
Stands for stream editor and it can perform lots of
functions on file like searching, find and replace,
insertion or deletion. Though most common use of
SED command in UNIX is for substitution or for find
and replace.
SED is a powerful text stream editor. Can do insertion,
deletion, search and replace(substitution).
SED command in unix supports regular expression
which allows it perform complex pattern matching.
$cat > osfile.txt

unix is great os. unix is opensource. unix is free os.


learn operating system.
unix linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn
unix .unix is a powerful.
Replacing or substituting string : Sed command is
mostly used to replace the text in a file. The below
simple sed command replaces the word “unix” with
“linux” in the file.

$sed 's/unix/linux/’ osfile.txt


Replacing the nth occurrence of a pattern in a line :
Use the /1, /2 etc flags to replace the first, second
occurrence of a pattern in a line. The below command
replaces the second occurrence of the word “unix”
with “linux” in a line.

$sed 's/unix/linux/2’ osfile.txt


Replacing all the occurrence of the pattern in a line :
The substitute flag /g (global replacement) specifies
the sed command to replace all the occurrences of the
string in the line.

$sed 's/unix/linux/g’ osfile.txt


Deleting lines from a particular file : SED command
can also be used for deleting lines from a particular
file. SED command is used for performing deletion
operation without even opening the file
Examples:
 To Delete a particular line say n in this example

$ sed '5d' filename.txt


Replacing string on a range of lines : You can specify a
range of line numbers to the sed command for
replacing a string.

$sed '1,3 s/unix/linux/’ osfile.txt


Viewing a file from x to y range –
sed -n '2,5p' a.txt
df command
Use df command to get a report on the system’s disk
space usage, shown in percentage and KBs.
df
If you want to see the report in megabytes, type
df -m
du command
If you want to check how much space a file or a
directory takes, the du (Disk Usage) command is the
answer. However, the disk usage summary will show
disk block numbers instead of the usual size format.
du
If you want to see it in bytes, kilobytes, and
megabytes, add the -h argument to the command line.

du -h
Shell Scripting
 A shell script is a list of commands in a computer program that
is run by the Unix shell which is a command line interpreter.
 A shell script usually has comments that describe the steps.
• The different operations performed by shell scripts are
• Automating the code compiling process.
• Running a program or creating a program environment.
• Completing batch
• Manipulating files.
• Linking existing programs together.
• Executing routine backups.
• Monitoring a system.
CLA
Arguments can be passed to a bash script during the
time of its execution, as a list, separated by space
following the script filename.
For instance, let’s pass a couple of parameters to our
script start.sh:

$start.sh development 100


Using Single Quote
If the input list has arguments that comprise multiple
words separated by spaces, they need to be enclosed in
single quotes.

$start.sh 'development mode' 100


Special Variables
$$
$0
$n
$#
$*
$@
$?
$!
Positional Parameters
echo "Username: $1";
echo "Age: $2";
echo "Full Name: $3";
Sr.No. Variable & Description
$0
1
The filename of the current script.

$n
2 These variables correspond to the arguments
with which a script was invoked.

$#
3
The number of arguments supplied to a script.
$*
All the arguments are double quoted. If a script
4
receives two arguments, $* is equivalent to $1
$2.
$@
All the arguments are individually double
5
quoted. If a script receives two arguments, $@ is
equivalent to $1 $2.
$?
6
The exit status of the last command executed.
$$
7
The process number of the current shell.
$!
8 The process number of the last background
CLA programs
echo "Number of argument passed: $#"
echo "Script name is $0"
echo "The 2nd argument passed is: $2"
echo "Arguments passed to script are: $*”
echo "Arguments passed to script are: $@”
echo "Exit status of last command that executed:$?"
echo "PID of current shell is: $$"
Difference between $* and $@
There is no difference if you do not put $* or $@ in
quotes. But if you put them inside quotes, then $@
will pass your parameters as separate parameters,
whereas $* will just pass all params as a single
parameter.
for TOKEN in $*
do
echo $TOKEN
done
Try this program with $@, “$*”, “$@” and see the
difference

./test.sh subhash "man shyam" sunil


Another Example
 Take these scripts (foo.sh and bar.sh) for testing:
 >> cat bar.sh
 echo "Arg 1: $1"
 echo "Arg 2: $2"
 echo "Arg 3: $3"
 echo
 >> cat foo.sh
 echo '$* without quotes:'
 ./bar.sh $*
 echo '$@ without quotes:'
 ./bar.sh $@
 echo '$* with quotes:'
 ./bar.sh "$*"
 echo '$@ with quotes:'
 ./bar.sh "$@"
>> ./foo.sh arg1 "arg21 arg22" arg3
$* without quotes:
Arg 1: arg1
Arg 2: arg21
Arg 3: arg22
$@ without quotes:
Arg 1: arg1
Arg 2: arg21
Arg 3: arg22
$* with quotes:
Arg 1: arg1 arg21 arg22 arg3
Arg 2:
Arg 3:
$@ with quotes:
Arg 1: arg1
Arg 2: arg21 arg22
Arg 3: arg3

Clearly, "$@" gives the behaviour that we generally want.


Variables
NAME=“Linux"
Age=20
readonly Age
unset NAME
Age=30
echo $NAME
echo $Age
Reading and printing a variable
echo "What is your name?"
read name
echo "Hello, $name"

echo -n "What is your name?"


read name
echo "Hello, $name"
Append something to the variable
And if you want to append something to the variable
value while printing it, use curly brackets around the
variable name as shown in the following example:

echo "What are you doing?"


read action
echo "You are ${action}ing."
Weak Quoting
If you want to bash to expand your argument, you can
use Weak Quoting:

world="World"
echo "Hello $world"
Strong Quoting
If you don't want to bash to expand your argument,
you can use Strong Quoting:

world="World"
echo 'Hello $world'
Comment
Single-line comments:
#This is a comment

Multi-line comments:
: '
This is a
Multi-line comments'

There should be no white space


between delimiter (‘ ‘)
Backspace characters
a=10
echo “Value of a is $a \n”

Value of a is 10 \n

a=10
echo -e "Value of a is $a \n”

Value of a is 10
Practice
Write a shell script to print the current working
directory and listing of file with appropriate message
Solution
echo "Your current working directory is:"
pwd

echo "These are the contents of this directory:"


ls -l
Shell Basic Operators
Arithmetic Operators
Relational Operators
Boolean Operators
String Operators
File Test Operators
Bourne shell has no any mechanism to perform simple
arithmetic it uses external programs like expr

val=`expr 2 + 2 `
echo "Total value : $val“

There must be spaces between operators and


expressions
Arithmetic Operators
a=10, b=3
What will be the output
echo $a + $b
echo `expr $a + $b`
echo `expr $a - $b`
What will the output? echo `expr $a * $b`
echo `expr $a \* $b`
echo `expr $a / $b`
echo `expr $a % $b`
a = $b
Important
All the conditional expressions should be inside square
braces with spaces around them,
 if [ $a == $b ]
 then All the conditional expressions should be inside
 echo "subhash" square braces with spaces around them,
 else
 echo "Ramesh"
 fi

 if [ $a != $b ]
 then
 echo "subhash"
 else
 echo "Ramesh"
 fi
Programs
Write a shell script that will add three integer numbers,
which are supplied by the user and then find their
average.
Floating point
add=`echo "scale=1; $a / $b " | bc`
Relational Operators
[ $a -eq $b ]
[ $a -ne $b ]
[ $a -gt $b ]
[ $a -lt $b ]
[ $a -ge $b ]
[ $a -le $b ]
Boolean Operators
[ ! $a -gt $b ]
[ $a -lt 20 -o $b -gt 100 ]
[ $a -lt 20 -a $b -gt 100 ]
String Operators
[ $a = $b ]
[ $a != $b ]
[ -z $a ]
[ -n $a ]
[ $a ]
The if...else statements
Unix Shell supports following forms of if…else
statement −
if statement
if-else statement
if..elif..else..fi statement (Else If ladder)
if..then..else..if..then..fi..fi..(Nested if)
if if
[ expression ] [ expression ]
then then
statement statement1
iffi[ expression1 ] else
then statement2
statement1 fi
statement2 if [ expression1 ]
. then
. statement1
elif [ expression2 ] statement2
then .
statement3 else
statement4 if [ expression2 ]
. then
. statement3
else .
statement5 fi
fi fi
Programs
 Write a shell script that will add two integers from command line
 Write a shell script to check whether a given number is positive
or negative or zero.
 Write a shell script to check whether a given number is even or
odd.
 The marks obtained by a student in 3 different subjects are input
through the keyboard. The student gets a division as per the
following rules:
Average above or equal to 60 - First division
Average between 50 and 59 - Second division
Average between 40 and 49 - Third division
Average less than 40 - Fail
Write a shell script to calculate the division obtained by the student.
Case statement
 case $variable-name in
 pattern1)
 command1 ... .... commandN
 ;;
 pattern2)
 command1 ... .... commandN
 ;;
 patternN)
 command1 ... .... commandN
 ;;
 *)
 esac
Example
CARS="bmw"
case "$CARS" in
"mercedes") echo "Headquarters - Affalterbach,
Germany" ;;
"audi") echo "Headquarters - Ingolstadt, Germany" ;;
"bmw") echo "Headquarters - Chennai, Tamil Nadu,
India" ;;
esac
Example
 echo "Enter a number"
 read num
 case $num in
 [0-9])
 echo "you have entered a single digit number"
 ;;
 [1-9][1-9])
 echo "you have entered a two-digit number"
 ;;
 [1-9][1-9][1-9])
 echo "you have entered a three-digit number"
 ;;
 *)
 echo "you have entered a wrong number"
 esac
 NOW=$(date +"%a")
 echo $NOW
 case $NOW in
 Mon)
 echo "Full backup";;
 Tue|Wed|Thu|Fri)
 echo "Partial backup";;
 Sat|Sun)
 echo "No backup";;
 *) ;;
 esac
Problem1
Car zeep and Bus
Input distance and vehicle type accordingly calculate
the rental
Do the same for command Line Argument
Car zeep and Bus
Input distance and vehicle type accordingly calculate
the rental
Program-1
Write a menu driven driven program to perform
following operations using case statement
1) List of files
2) Today’s date
3) count number of lines and words in a file names abc
4) Display number of command line arguments.
5) Exit
 read choice
 case "$choice" in
 1) ls -l;;
 2) date;;
 3) echo "Number of lines"
 wc -l abc
 echo "number of characters"
 wc -c abc
 ;;
 4)echo "$#";;
 5) clear;;
 *)echo "Wrong choice"
 esac
Program-2
Write a program to check a given character is vowel,
digit or other character using case statement.
read choice
case "$choice" in
a|e|i|o|u)echo "Vowel";;
[0-9])echo "Digits";;
*)echo "other"
esac
Program 3
Write a program to check a given n umber is Even or
Odd using case statement.
read number
case `expr $number % 2` in
0) echo "Even";;
1) echo "Odd"
Esac
While: Looping
Syntax:

While condition is true


do
Commands
done
Example
Print numbers from 1 to 10

a=1
while [ $a -le 10 ]
do
 echo $a
 a=`expr $a + 1`
done
Program
Print Multiplication table of a given number
Program to do
 Write a program to read student name rollno and marks in the
same line, and then writes the line to a file student. It then
prompts you for more entries
 answer=y;
 while [ $answer = y ]
 do
 read name rollno marks
 echo "$name|$rollno|$marks" >>student
 echo "Enter any more"
 read an
 case $an in
 y*|Y*) answer=y;;
 n*|N*) answer=n;;
 *) answer=y;;
 esac
 done
for : looping
Syntax: Looping with a list
 for variable in list
do
Commands
done
Example
for file in student subhash.sh third
do
cp $file $file.bak
echo $file copied to $file.bak
done
Program to do
Search the patterns provided through command line
Arguments in a file .
Input:
./subhash.sh if for while grep

for pattern in "$@"


do
grep "$pattern" subhash.sh || echo "Not found"
done
How to define range in for loop
for pattern in {1..10}
do
echo $pattern
done
What will be the output?
for pattern in {1..10..4}
do
echo $pattern
done
C Style for loop
fact=1;
n=3
for((i=1;i<=$n;i++))
do
fact=`expr $fact \* $i`
done
echo $fact
Until loop
a=10
until [ $a -gt 14 ] a=10
while [ $a -gt 14 ]
do
do
 echo $a echo $a
 a=`expr $a + 1` a=`expr $a + 1`
 done
done
a=0
while [ $a -lt 10 ]
do
 echo $a
 if [ $a -eq 5 ]
 then
 break
 fi
 a=`expr $a + 1`
done
0
1
2
3
4
5
for var1 in 1 2 3
do
 for var2 in 0 5
 do
 if [ $var1 -eq 2 -a $var2 -eq 0 ]
 then
 break 2
 else
 echo "$var1 $var2"
 fi
 done
done
1 0
1 5
for var1 in 1 2 3
do
 for var2 in 0 5
 do
 if [ $var1 -eq 2 -a $var2 -eq 0 ]
 then
 break
 else
 echo "$var1 $var2"
 fi
 done
done
1 0
1 5
3 0
3 5
Average of given numbers
 n=5
 m=$n
 sum=0
 array=(12 22 34 46 57)
 while [ $n -gt 0 ]
 do
 num=${array[`expr $n - 1`]}
 sum=`expr $sum + $num`
 n=`expr $n - 1`
 done
 avg=`echo "$sum / $m" | bc -l`
 printf '%0.3f' "$avg"
Using for loop
 n=5
 m=$n
 sum=0
 array=(12 22 34 46 57)
 for((i=0;i<$n;i++))
 do
 num=${array[`expr i`]}
 sum=`expr $sum + $num`
 done
 avg=`echo "$sum / $m" | bc -l`
 printf '%0.3f' "$avg"
NUMS="1 2 3 4 5 6 7“
for NUM in $NUMS
do
 Q=`expr $NUM % 2`
 if [ $Q -eq 0 ]
 then
 echo "Number is an even number!!"
 continue
 fi
 echo "Found odd number"
done
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
while
 a=0
 while [ "$a" -lt 5 ]
 # this is loop1
 do
 b="$a"
 while [ "$b" -ge 0 ]
 # this is loop2
 do
 echo -n "$b "
 b=`expr $b - 1`
 done
 echo
 a=`expr $a + 1`
 done
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
Palindrome
Given a number num, find whether the given number
is palindrome or not using Bash Scripting.
Examples:
Input : 666
Output : Number is palindrome
Input : 45667 Output : Number is NOT palindrome
num=1214
s=0
rev=0
temp=$num
while [ $num -gt 0 ]
do
s=$(( $num % 10 ))
num=$(( $num / 10 ))
rev=`expr $rev \* 10 + $s`
done
if [ $temp -eq $rev ];
then
echo "Number is palindrome"
else
echo "Number is NOT palindrome"
fi
Program
Merge the contents of two files into one file
Write a Shell script to accept a filename as argument
and displays the last modification time if the file exists
and a suitable message if it doesn't.
Write the shell script to take file name as input and if
the file exists then print the number of lines and also
print 10th line of that file.
#Script to see whether given number is
positive or negative
 # !/bin/bash
 echo -n "Enter a number:"
 read num
 if test $num –eq 0
 then
 echo "$num is zero"
 else
 if test $num -gt 0
 then
 echo "$num is positive"
 else
 echo "$num is negative"
 fi
 fi
#Check whether a given number is even or
odd.
clear
echo -n "Enter a number : "
read num
rem=`expr $num % 2`
if [ $rem -eq 0 ]
then
echo "The number is even"
else
echo "The number is odd"
fi
The marks obtained by a student in 3 different subjects
are input through the keyboard. The student gets a
division as per the following rules:
Average above or equal to 60 - First division
Average between 50 and 59 - Second division
Average between 40 and 49 - Third division
Average less than 40 - Fail

Write a shell script to calculate the division obtained by


the student.
 echo "Enter marks in three subjects"
 read m1
 read m2
 read m3
 sum=`expr $m1 + $m2 + $m3`
 per=`expr $sum / 3`
 if [ $per -ge 60 ]
 then
 echo "First division"
 else
 if [ $per -ge 50 ]
 then
 echo "Second Division"
 else
 if [ $per -ge 40 ]
 then
 echo "Third Division"
 else
 echo "Fail"
 fi
 fi
 fi
Program-1
write-a-shell-program-to-count-the-characters-count-
the-lines-and-the-words-in-a-particular-file
 echo Enter your name
 read name
 echo Enter your program name
 read prog
 echo Enter your enrolement number
 read enrol
 clear
 echo Details you entered
 echo Name:$name
 echo Program Name:$prog
 echo Enrolement Number:$enrol
Program-2(Power)
 echo \"Input number\"
 read no
 echo \"Input power\"
 read power
 counter=0
 ans=1

 while [ $power -ne $counter ]


 do
 ans=\`expr $ans \\* $no\`
 counter=\`expr $counter + 1\`
 Done
 echo \"$no power of $power is $ans\"
Program-3 Largest among three numbers
 echo Enter 3 numbers with spaces in between
 read a b c
 l=$a
 if [ $b -gt $l ]
 then
 l=$b
 fi
 if [ $c -gt $l ]
 then
 l=$c
 fi
 echo Lagest of $a $b $c is $l
Sum, Average and product of 4 integer
numbers
echo Enter four integers with space between
read a b c d
sum=\`expr $a + $b + $c + $d\`
avg=\`expr $sum / 4\`
dec=\`expr $sum % 4\`
dec=\`expr \\( $dec \\* 1000 \\) / 4\`
product=\`expr $a \\* $b \\* $c \\* $d\`
echo Sum=$sum
echo Average=$avg.$dec
echo Product=$product
Addition, Subtraction and Multiplication of command line
Arguments
add=\`expr $1 + $2\`
sub=\`expr $1 - $2\`
mul=\`expr $1 \\* $2\`
echo Addtion of $1 and $2 is $add
echo Subtraction of $2 from $1 is $sub
echo Multiplication of $1 and $2 is $mul
Write a shell script to take name as a input and display a greeting message to the
user by checking system clock. (Ex :- Hello John Good Morning in morning time
else Hello John Good Afternoon in afternoon time else Hello John Good Evening
in Evening time)
 check=\`date +%H\`
 echo $check
 if [ $check -ge 06 -a $check -le 12 ]
 then
 echo \"Good morning\"
 elif [ $check -ge 12 -a $check -le 17 ]
 then
 echo \"Good afternoon\"
 else
 echo \"Good evening\"
 fi
Array
NAME[0]="Apple"
NAME[1]="Mango"
NAME[2]="Banana"
NAME[3]="Guaua"
NAME[4]="orange"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
NAME[0]="Apple"
NAME[1]="Mango"
NAME[2]="Banana"
NAME[3]="Guaua"
NAME[4]="orange"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
Array
declare -a Unix=('Mango' 'Apple' 'Banana' 'Orange');
echo ${#Unix[@]}
echo ${#Unix}
echo ${#Unix[3]}
declare -a Unix=('Mango' 'Apple' 'Banana' 'Orange');
echo ${Unix[@]:2:2};
declare -a Unix=('Mango' 'Apple' 'Banana' 'Orange');
echo ${Unix[2]:0:4};
read -a array
for i in "${array[@]}"
do
 echo $i
done
Sorting
Given an array arr sort the array in ascending order
using bash scripting.
Examples:
Input : 9 7 2 5
Output : Array in sorted order : 2 5 7 9
arr=(10 8 20 100 12)
echo "Array in original order"
echo ${arr[*]}
for ((i = 0; i<5; i++))
do
for((j = 0; j<5-i-1; j++))
do
Array Initialization
if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
then
temp=${arr[j]}
arr[$j]=${arr[$((j+1))]}
arr[$((j+1))]=$temp
fi
done
done
echo "Array in sorted order :"
echo ${arr[*]}
read n
for ((i = 0; i<n; i++))
do
read arr[i]
Done
echo "Array in original order"
echo ${arr[*]}
for ((i = 0; i<5; i++))
do
for((j = 0; j<5-i-1; j++)) Array Reading elements one
do by one
if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
then
temp=${arr[j]}
arr[$j]=${arr[$((j+1))]}
arr[$((j+1))]=$temp
fi
done
done
echo "Array in sorted order :"
echo ${arr[*]}
read -a arr
echo "Array in original order"
echo ${arr[*]}
for ((i = 0; i<5; i++))
do
for((j = 0; j<5-i-1; j++))
do
if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
Array Reading at a time
then
temp=${arr[j]}
arr[$j]=${arr[$((j+1))]}
arr[$((j+1))]=$temp
fi
done
done
echo "Array in sorted order :"
echo ${arr[*]}
Program
Write a program to check a given n umber is Even or
Odd using case statement.
read number
case `expr $number % 2` in
0) echo "Even";;
1) echo "Odd"
Esac
Equal operator (=)
str1="ShellScript";
str2="Shell";
if [ $str1 = $str2 ]
then
echo "Both string are same";
else
echo "Both string are not same";
fi
Another program

str1="Shell Script";
str2="Shell";
if [ $str1 = $str2 ]
then
echo "Both string are same";
else
echo "Both string are not same";
fi
Not Equal to operator (!=)
str1="ShellScript";
str2="Shell";
if [ $str1 != $str2 ]
then
echo "Both string are same";
else
echo "Both string are not same";
fi
Other Operators
Less then (\<)
Greater then (\>)
[ -n Operand ]
[ -z Operand ]
Program
Write a shell script to input the name of a file as
command line argument and display the number of
characters, words and lines in the file.
Solution
 for F in $*
 do
 c=$( wc -c < ${F} )
 echo "Number in characters in ${F} is $c"
 echo
 w=$( wc -w < ${F} )
 echo "Number in words in ${F} is $w"
 echo
 l=$( wc -l < ${F} )
 echo "Number in lines in ${F} is $l"
 done
String
 Identify String Length inside Bash Shell Script
 var="Welcome to the GLA University"
 echo ${#var}
29

 Extract a Substring from a Variable inside Bash Shell Script


 ${string:position}
 var="Welcome to the GLA University"
GLA University
 echo ${var:15}
Welcome to the
 echo ${var::15}
GLA U
 echo ${var:15:5}
var="Welcome"
echo ${var:3}
come
echo ${var::4} Welc
echo ${var:3:2} co
Finding Index
test="AaBbCcDdEeFfGg“
testa=`expr index "$test" C` testa is in position: 5
testb=`expr index "$test" D` testb is in position: 7
testc is in position: 9
testc=`expr index "$test" E`
testd is in position: 0
testd=`expr index "$test" Z`

echo "testa is in position: $testa"


echo "testb is in position: $testb"
echo "testc is in position: $testc"
echo "testd is in position: $testd"
Finding Index
STRING="wwwis ist a string"
SUBSTRING="hat" 9
a=`expr index "$STRING" "$SUBSTRING"`
echo $a
Find the occurrence of a substring into a
string
t="Subhash Chand Agrawal os lab"
searchstring="Agrawal"
rest=${t#*$searchstring}
echo $(( ${#t} - ${#rest} - ${#searchstring} ))
Shortest Substring Match
Following syntax deletes the shortest match of
$substring from front of $string
${string#substring}

Following syntax deletes the shortest match of


$substring from back of $string
${string%substring}
Example
filename="bash.string.txt"
echo ${filename#*.}
string.txt
echo ${filename%.*} bash.string

filename="bash.string.txt"
echo ${filename#*.st} ring.txt
bash.strin
echo ${filename%g.*}
Longest Substring Match
${string##substring}
${string%%substring}

filename="bash.string.txt"
echo ${filename##*.} txt
bash
echo ${filename%%.*}
Find and Replace String Values inside
Bash Shell Script
${string/pattern/replacement}
filename="bash.string.txt"
echo ${filename/str*./operations.}
bash.operations.txt

Replace all the matches


${string//pattern/replacement}

filename="Path of the bash is /bin/bash“


echo ${filename//bash/sh}
Path of the sh is /bin/sh
Exercise
String a=“Life is like a snowball. The important thing
is finding wet snow and a really long hill.”
In this exercise, you will need to change string a. First
create a variable mys and assign it the original saying
value. Then re-assign it with a new changed value
using the string operations and following the 4 defined
changes:
Change1: replace the first occurrence of 'snow' with
'foot'.
Change2: delete the second occurrence of 'snow'.
Change3: replace 'finding' with 'getting'.
Change4: delete all characters following 'wet'.
 a="Life is like a snowball. The important thing is finding wab wet
snow and a really long hill."
 mys=$a
 change1=${mys/snow/foot}
 echo $change1
 change2=${change1//snow/}
 echo $change2
 change3=${change2/finding/getting}
 echo $change3
 loc=`expr index "$change3" 'w'`
 mys=${change3::$loc+2}
 echo $mys
https://www.shellscript.sh/tips/pattern-substitution/
https://www.learnshell.org/en/Basic_String_Operation
s
https://www.thegeekstuff.com/2010/07/bash-string-
manipulation/
System Call
A request for the operating system to do something on
behalf of the user's program.
The system calls are functions used in the kernel itself.
To the programmer, the system call appears as a
normal C function call.
The C compiler uses a predefined library of functions
(the C library) that have the names of the system calls.
 The library functions typically invoke an instruction
that changes the process execution mode to kernel
mode and causes the kernel to start executing code for
system calls.
UNIX system calls are used to manage the file system,
control processes, and to provide interprocess
communication.
Creating a Channel creat()
open()
close()
Input/Output read()
write()
Random Access lseek()
Channel Duplication dup()
File Structured Aliasing and Removing files link()
Related Calls unlink()
File Status stat()
fstat()
Access Control access()
chmod()
chown()
umask()
Device Control ioctl()
http://www.di.uevora.pt/~lmr/syscalls.html
File Structure Related System
Calls

1) Create: Used to Create a new empty file.


Syntax in C language:
int creat(char *filename, mode_t mode)
Parameter :
filename : name of the file which you want to create
mode : indicates permissions of new file.
Returns :
return first unused file descriptor (generally 3 when
first creat use in process because 0, 1, 2 fd are
reserved)
return -1 when error
How it work in OS Create new empty file on disk
Create file table entry
Set first unused file descriptor to point to file table
entry
Return file descriptor used, -1 upon failure
 #include <stdio.h>
 #include <sys/types.h> /* defines types used by sys/stat.h
*/
 #include <sys/stat.h> /* defines S_IREAD & S_IWRITE
*/
 int main()
 {
 int fd;
 fd = creat("datafile.dat", S_IREAD | S_IWRITE);
 if (fd == -1)
 printf("Error in opening file\n");
 else {
 printf(“file opened for read/write access\n");
 printf(“file is currently empty\n");}
 close(fd);
If mode is defined as 0666, What does it mean?
The mode is usually specified as an octal number such
as 0666 that would mean read/write permission for
owner, group, and others or the mode may also be
entered using manifest constants defined in the
 The following is a sample of the manifest constants for the mode
 argument as defined in /usr/include/sys/stat.h:
 #define S_IRWXU 0000700 /* -rwx------ */
 #define S_IREAD 0000400 /* read permission, owner */
 #define S_IRUSR S_IREAD
 #define S_IWRITE 0000200 /* write permission, owner */
 #define S_IWUSR S_IWRITE
 #define S_IEXEC 0000100 /* execute/search permission, owner
*/
 #define S_IXUSR S_IEXEC
 #define S_IRWXG 0000070 /* ----rwx--- */
 Multiple mode values may be combined by or'ing (using the | operator)
 the values together as demonstrated in the above sample program.
open: Used to Open the file for reading, writing or
both.
 Syntax in C language
int open (const char* Path, int flags [, int mode ]);
Parameters
 Path : path to file which you want to use
use absolute path begin with “/”, when you are not work in
same directory of file.
Use relative path which is only file name with extension,
when you are work in same directory of file.
 flags : How you like to use
O_RDONLY: read only, O_WRONLY: write only,
O_RDWR: read and write, O_CREAT: create file if it
doesn’t exist, O_EXCL: prevent creation if it already exists
 The allowable option_flags as defined in
"/usr/include/fcntl.h" are:
 #define O_RDONLY 0 /* Open the file for reading
only */
 #define O_WRONLY 1 /* Open the file for writing
only */
#define O_RDWR 2 /* Open the file for both
reading and writing*/
#define O_CREAT 00400 /*open with file create */
#define O_EXCL 02000 /* exclusive open */
#include <fcntl.h> /* defines options flags */
#include <sys/types.h> /* defines types used by sys/stat.h */
#include <sys/stat.h> /* defines S_IREAD & S_IWRITE */
static char message[] = "Hello, world";
int main()
{
int fd;
char buffer[80];
/* open datafile.dat for read/write access (O_RDWR)
create datafile.dat if it does not exist (O_CREAT)
return error if datafile already exists (O_EXCL)
permit read/write access to file (S_IWRITE | S_IREAD)
*/
fd = open("datafile.dat",O_RDWR | O_CREAT | O_EXCL,
S_IREAD | S_IWRITE);
if (fd != -1)
{
printf(“file opened for read/write access\n");
write(fd, message, sizeof(message));
lseek(fd, 0L, 0); /* go back to the beginning of the file */
if (read(fd, buffer, sizeof(message)) == sizeof(message))
printf("\"%s\" was written to file\n", buffer);
else
printf("*** error reading file ***\n");
close (fd);
}
else
printf("*** file already exists ***\n");
exit (0);
}
 #include <stdio.h>
 #include <fcntl.h> whence new position
 0 offset bytes into the file
int main()
1 current position in the file plus offset
 { 2 current end-of-file position plus offset
 int fd;
 long position;
 fd = open("datafile.dat", O_RDONLY);
 if ( fd != -1)
 {
 position = lseek(fd, 0L, 2); /* seek 0 bytes from end-of-file */
 if (position != -1)
 printf("The length of datafile.dat is %ld bytes.\n", position);
 else
 perror("lseek error");
 }
 else
 printf("can't open datafile.dat\n");
 close(fd);
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{

// make two process which run same


// program after this instruction
fork();
printf("Hello world!\n");
return 0;
}
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
int fd;

fd = open("foo.bar",O_WRONLY | O_CREAT, S_IREAD | S_IWRITE );


if (fd == -1)
{
perror("foo.bar");
exit (1);
}
close(1); /* close standard output */
dup(fd); /* fd will be duplicated into standard out's slot */
close(fd); /* close the extra slot */
printf("Hello, world!\n"); /* should go to file foo.bar */
exit (0); /* exit() will close the files */
}

The dup() system call duplicates an


open file descriptor
#include <stdio.h>
#include <fcntl.h> The UNIX system calls that transform a
#include <sys/types.h>executable binary file into a process are the
#include <sys/stat.h> "exec" family of system calls. The
int main() prototypes for these calls are:
{
int fd;
if ( fork() != 0)
wait ((int *) 0);
else
{
execl ("/bin/mkdir", "mkdir", "newdir", (char *) NULL);
fprintf (stderr, "exec failed!\n");
exit (1); Takes the path name of an executable
} program (binary file) as its first argument.
The rest of the arguments are a list of
command line arguments to the new program
(argv[]).
 if ( (fd = open("newdir/foo.bar", O_RDWR | O_CREAT, 0644))
== -1)
 {
 fprintf (stderr, "open failed!\n");
 exit (2);
 }
 write (fd, "Hello, world", 14);
 close (fd);
 exit (0);
 }


#include <stdio.h>
#define EVER ;;
int main()
{
int process;
char line[81];
for (EVER)
{
fprintf(stderr, "cmd: ");
if ( gets (line) == (char *) NULL) /* blank line input */
exit (0);
/* create a new process */
process = fork ();
if (process > 0) /* parent */
wait ((int *) 0); /* null pointer - return value not saved */
else if (process == 0) /* child */
{ /* execute program */
execlp (line, line,(char *) NULL);
/* some problem if exec returns */
fprintf (stderr, "Can't execute %s\n", line);
exit (1);
}
else if ( process == -1) /* can't create a new process */
{
fprintf (stderr, "Can't fork!\n");
exit (2);
}
}
} Same as execl(), except that the program
name doesn't have to be a full path name,
and it can be a shell program instead of an
executable module:
Alarm()
Every process has an alarm clock stored in its system-data segment.
When the alarm goes off, signal SIGALRM is sent to the calling
process.
unsigned int alarm(seconds)
unsigned int seconds;
where seconds defines the time after which the UNIX system
sends the SIGALRM signal to the calling process.

Signal()
The UNIX system provides a facility for sending and receiving
software interrupts, also called SIGNALS.
Signals are sent to a process when a predefined condition happens.
The number of signals available is system dependent.
int (* signal ( signal_name, function ))
 #include <stdio.h>
 #include <sys/signal.h>
 int times_up();
 void main()
 {
signal (SIGALRM, times_up); // go to the times_up function */ when the alarm
goes off.
 alarm (10); /* set the alarm for 10 seconds */
 for (;;) /* endless loop. */
 ; /* hope the alarm works. */
 }
 int times_up(int sig)
 {
 printf("Caught signal #< %d >n", sig);
 printf("Time's up!!\n");
 exit(sig); /* return the signal number */
 }

You might also like