OS Lab by Raushan Sir
OS Lab by Raushan Sir
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
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.
head -n 5 core.c
tail
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
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
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:
$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
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'
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
val=`expr 2 + 2 `
echo "Total value : $val“
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:
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
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
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
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 */
}