Lab02 Reading Material
Lab02 Reading Material
Lab02 Reading Material
Syntax :
tr [OPTION] … SET1 [SET2]
Options :
Option Description
-c Complements the set of characters in string. i.e., operations apply to characters not in
the given set
-d Deletes characters in the first set from the output
-s Replaces repeated characters listed in set1 with single occurrence
-t Truncates set1
To convert from lower case to upper case, the predefined sets in tr can be used. The [:lower:]
and [:upper:] represent set of lower case and upper case characters. The tr '[:lower:]' '[:upper:]'
command matches lower case characters and transfer them to corresponding uppercase
characters.
Eg : echo "you Are the Best" | tr [:lower:] [:upper:]
YOU ARE THE BEST
By default tr will repeat the last character of the second set for all additional characters in the
first set if the first and second sets are of different lengths. Consider the following example.
Page 1 of 20
echo "Difficulties are blessings." | tr 'abcde' 'XYZ'
DiffiZultiZs XrZ YlZssings.
The last character of the second set is used to match any letter from c-e. Using the –t (truncate)
option limits the matching to the length of the second set.
echo "Difficulties are blessings." | tr -t 'abcde' 'XYZ'
DiffiZulties Xre Ylessings.
The additional characters ‘d-e’ are not replaced when -t option is used. Use the -c option to
search and replace compliment of a pattern in first set. In the following example, any character
that is not ‘te’ is matched and translated to ‘B’.
echo "you Are the Best" | tr -c 'te' 'B'
BBBBBBeBtBeBBeBtB
To delete specific characters use the -d option. This option deletes characters in the first set
specified. The following example removes any occurrence of ‘c’ and ‘e’.
echo "success is not an accident" | tr -d 'ce'
suss is not an aidnt
We can use the -s option to squeeze repeated occurrences of characters in a set. This removes the
repeated instances of a character. In the following example, a string with too many spaces is
squeezed, i.e., removed.
echo "Failures are stepping stone towards success"| tr -s ' '
Failures are stepping stone towards success
Syntax :
cut [OPTION] … [FILE]...
Options :
Option Description
-b Extracts the specific bytes
-c Extracts the specific characters
-d Replaces TAB [the default delimiter] to the specified delimiter
-f Cuts by fields (1, 2, 3...)
Page 2 of 20
The byte/character positions can be a single number, list of comma separated numbers, or a
range of numbers.
The -d option is normally used in conjunction with -f option to specify the field that should be
cut. For demonstrating the use of these options, data.txt file is created with following content.
cat > data.txt
Rhonda,Byrne,The Secreat, Rs. 750
Dale,Carnegie,Stop Worring And Start Living, Rs. 250
Monica,Sheehan,Be Happy, Rs. 240
Napolean,Hill,The Law of Success, Rs. 950
Robert,Kiyosaki,Rich Dad Poor Dad, Rs. 420
^C
The delimiter is set to comma with -d ','. The cut command can then pull out the fields of interest
with -f option. In the following example, the first field is cut.
Example of field selection based on delimiter :
cut -d ',' -f 1 data.txt
Rhonda
Dale
Monica
Napolean
Robert
Page 3 of 20
Multiple fields can be cut by passing a comma separated list or by specifying a range of
numbers.
2. What is Shell?
A program that interprets commands and allows a user to execute commands by typing them
manually at a terminal, or automatically in programs called shell scripts.
A shell is not an operating system. It is a way to interface with the operating system and execute
commands.
Login shell is BASH = Bourne Again Shell
Bash is a shell written as a free replacement to the standard Bourne Shell (/bin/sh) originally
written by Steve Bourne for UNIX systems. It has all the features of the original Bourne Shell,
plus additions that make it easier to program with and use from the command line. Since it is
Free Software, it has been adopted as the default shell on most Linux systems.
Many commands accept arguments which are file names. For example:
ls -l main.c
prints information relating to the file main.c.
The shell provides a mechanism for generating a list of file names that match a pattern.
For example,
ls -l *.c
generates, as arguments to ls, all file names in the current directory that end in .c.
The character * is a pattern that will match any string including the null string. This
mechanism is useful both to save typing and to select names according to some pattern.
Page 4 of 20
Following are the special characters interpreted by the shell called as Wild cards.
Command What does the command do?
* Matches any number of characters including none
? Matches a single character
[ijk] Matches a single character either i , j or k
[!ijk] Not i, j or k
[x-z] At least a single character within this ASCII range
[!x-z] Not a single character within this range
Examples:
ls a (output is only a if a is a file, output is the content of a if a is a
directory)
ls ar* ( all those that start with ar)
ls *vict ( all those files that end with vict)
ls *[ijk] (all files having i ,j or k as the last character of the filename)
ls *[b-r] (all files which have at least any character between b and r as the last
character of the filename)
ls * ( all files)
Examples:
ls a?t matches all those files of three characters with a as the first and t as the
third character and any character in between
ls ?oo matches all three character files whose filename end with oo
Page 5 of 20
2.1 Quoting
Characters that have a special meaning to the shell, such as < > * ? | &, are called
metacharacters. Any character preceded by a \ is quoted and loses its special meaning, if any.
The \ is elided so that
echo \?
will echo a single ? and
echo \\
will echo a single \
\ is convenient for quoting single characters. When more than one character needs quoting the
above mechanism is clumsy and error prone. A string of characters may be quoted by enclosing
the string between single quotes.
For example,
echo xx'****'xx
will echo
xx****xx
The quoted string may not contain a single quote but may contain new lines, which are
preserved. This quoting mechanism is the most simple and is recommended for casual use. A
third quoting mechanism using double quotes is also available that prevents interpretation of
some but not all metacharacters.
3. Shell Scripts
The shell may be used to read and execute commands contained in a file.
As a simple case, assume that we have a scenario where commands who, ls and date are
executed one after the other.
To write shell scripts, open a new file in gedit (say gedit firstShellPgm)
Type all the commands that you want to get executed one after the other. i.e. who, ls and date.
The file content will be now
As stated earlier, the shell may be used to read and execute commands contained in a file.
To read and execute, the file use the following in command line
sh calls the shell to read commands from file. Such a file is called a command procedure or shell
procedure or shell script.
Page 6 of 20
This produces the output as shown in Figure 1.
Arguments may be supplied with the call and are referred to in file using the positional
parameters $1, $2, ....
For example, if the file secondShellPgm contains
then
sh secondShellPgm CPSec first
Page 7 of 20
Figure 2: Output of the sh secondShellPgm CPSec first
When the file executes, the first argument (CPSec in the previous example) replaces $1, second
argument replaces $2 …….
So
echo The parameter1 is $1 and Parameter 2 is $2
is equivalent to
echo The parameter1 is CPSec and Parameter 2 is first
and
who|grep $1*
is equivalent to
who|grep CPSec*
and
ls -l $2*
is equivalent to
ls -l first*
#this script asks user to input his name and then prints his name
echo What is your name \?
Page 8 of 20
read name
echo Hello $name. Happy Programming.
You must have noticed \ symbol before? This can be avoided if the message to be displayed is
enclosed in quotes. This script causes the name entered by you is stored in the variable name.
Also, while using in echo statement, this variable name is attached with $ indicating that name is
a variable, and extract the value stored in the variable name and use it in place of it.
The output is:
What is your name ?
john
Hello john. Happy Programming.
NOTE: The symbol quoting expr can be found on key having Tilde (~) below ESC key.
Page 9 of 20
6. Variables in Shell
To process data, it must be kept in computer’s RAM. RAM is divided into small locations, and
each location had unique number called memory location/address, which is used to hold the data.
Programmer can give a unique name to this memory location/address called memory variable or
variable [It is a named storage location that may take different values, but only one at a time]. In
Linux (Shell), there are two types of variable:
(1) System variables - Created and maintained by Linux itself. This type of variable defined in
CAPITAL LETTERS.
(2) User defined variables (UDV) - Created and maintained by user.
Caution: Do not modify System variables. This can some time create problems.
You can see the current values of these variables by typing echo $variable name
Example: echo $HOME
Examples:
number=10 # this is ok
Page 10 of 20
Rules for Naming variable name (Both UDV and System Variable)
1. Variable name must begin with Alphanumeric character or underscore character,
followed by one or more Alphanumeric character.
Examples of valid shell variable are:
HOME
SYSTEM_VERSION
vech
number
2. Don't put spaces on either side of the equal sign when assigning value to variable.
For example, in following variable declaration there will be no error
number=10
But there will be problem for any of the following variable declaration:
number =10
number= 10
number = 10
4. You can define NULL variable as follows [NULL variable is variable which has no value
at the time of definition]
For example
vech=
vech=""
Try to print it's value by issuing the command echo $vech
Nothing will be shown because variable has no value i.e. NULL variable.
Page 11 of 20
7. Decision making constructs in Shell
What computer know is 0 (zero) and 1 that is Yes or No.
To make this idea clear, lets take the help of bc - Linux calculator program. Type
bc
After this command bc is started and waiting for your commands, i.e. give it some calculation as
follows type 5 + 2 as:
5+2
7
7 is response of bc i.e. addition of 5 + 2.
Now see what happened if you type 5 > 2
5>2
1
1 is response of bc, How? bc compare 5 with 2 as, Is 5 is greater than 2, bc gives the answer as
'YES' by showing 1 as value. Now try
5<2
0
0 indicates FALSE. i.e., Is 5 is less than 2?, the answer NO indicated by bc is by showing 0.
Remember in bc, logical operations always returns true (1) or false (0).
Try following in bc to clear your Idea and not down bc's response.
5 > 12
5 == 10
5 != 2
5 == 5
1= < 2
It means whenever there is any type of comparison in Linux Shell, it gives only one of the two
answers YES or NO.
Remember bc and Linux Shell uses two different ways to show True/False values
Value Shown in bc as Shown in Linux Shell as
True/Yes 1 0
False/No 0 Non - zero value
Page 12 of 20
7.1. if condition
if condition is used for decision making in shell script. If the given condition is true then
command1 is executed.
Syntax:
if condition
then
command1
...
...
fi
Page 13 of 20
there is no output because our condition is not true (no -45 is not greater than 0) hence echo
statement is skipped.
For last statement we have not supplied any argument hence error ispostive: 1: test: -gt:
unexpected operator, is generated by shell , to avoid such error we can test whether command
line argument is supplied or not.
Page 14 of 20
Logical Operators
Logical operators are used to combine two or more condition at a time
Operator Meaning
! expression Logical NOT
expression1 -a expression2 Logical AND
expression1 -o expression2 Logical OR
7.2 if...else...fi
If given condition is true then command1 is executed otherwise command2 is executed.
Syntax:
if condition
then
condition is zero (true - 0)
execute all commands up to else statement
else
if condition is not true then
execute all commands up to fi
fi
For e.g. Write Script in file isPos as follows:
if test $1 -gt 0
then
echo "$1 number is positive"
else
echo "$1 number is negative"
fi
Do the following:
chmod +x isPos
sh isPos 5
5 number is positive
sh isPos -45
-45 number is negative
sh isPos
You must supply one integers
sh isPos 0
0 number is negative
Page 15 of 20
Detailed explanation
First script checks whether command line argument is given or not, if not given then it print error
message as "You must supply one integers". if statement checks whether number of argument
($#) passed to script is not equal (-eq) to 0, if we passed any argument to script then this if
statement is false and if no command line argument is given then this if statement is true. And
finally statement exit 1 causes normal program termination with exit status 1.
The last sample run sh isPos 0 , gives output as "0 number is negative", because given argument
is not > 0, hence condition is false and it's taken as negative number. To avoid this replace
second if statement with if test $1 -ge 0.
8. Exercises
Exercise 1
Write a shell script to display all the files in the present working directory whose file name starts
with the word given by positional parameter 1 and ends with the word given by positional
parameter 2.
Exercise 2
Write a shell script to display the total number of files in your present working directory.
Exercise 3
Write a shell script to ask user to enter a command and execute it.
Exercise 4
Write a Shell script which accepts two numbers a and b from the user directly and displays the
result of a2+b2. The shell script also takes a parameter. This parameter is added to previously
2 2
computer (a +b ) value and displays the final result.
Exercise 5
Write a Shell script which accepts three numbers a, b and c from the user directly and displays
the result of ax2+bx+c. The shell script takes the value of x as a parameter.
Exercise 6
Write a program to find the largest of 2 Numbers
(A) Take Numbers from user using read command
(B) Take Numbers from user as command line arguments
Exercise 7
Write a program to find the largest of 3 Numbers
(A) Take Numbers from user using read command
(B) Take Numbers from user as command line arguments
Exercise 8
Take radius as user input and calculate Area and Circumference of a circle if radius is greater
than 5
Page 16 of 20
ADDITIONAL QUESTIONS
Question #1
Write a shell script program named Lab3_1.sh which accepts a string from the user. The
shell script program should print the message “The entered string <string> is a directory
under the current working directory” if the string user entered is a directory under the
present working directory. Else the program should print the message “The entered string
<string> is NOT a directory under the present working directory”.
Question #2
Write a shell script program named Lab3_2.sh to take 3 sides of a triangle as command
line argument. Find whether the inputs can form a triangle. If yes, then find the perimeter
of the triangle and check whether the triangle is a scalene triangle. Display appropriate
messages for invalid data [like negative numbers, not a triangle etc ..].
Note: If A, B and C are three sides of a triangle, then the necessary condition for a valid
triangle is
A + B > C and A – B < C
Exercise Solutions
ex 1: ls -dp "$1"*"$2" | grep -v /
ex 2 : ls -l | wc -l
Page 17 of 20
ex 5:echo 'enter the value of a:'
read a
echo 'enter the value of b:'
read b
echo 'enter value of c :'
read c
x=$1
g=`expr $a \* $x \* $x`
h=`expr $b \* $x`
echo result is :`expr $g + $h + $c`
ex 6: (A)
echo 'enter first number :'
read a
echo 'enter second number:'
read b
if test $a -gt $b
then
echo $a is greater than $b
else
echo $b is greater than $a
fi
(B)
a=$1
b=$2
if test $a -gt $b
then
echo $a is greater than $b
else
echo $b is greater than $a
fi
ex 7: (A)
echo 'enter first number:'
read a
echo 'enter second number:'
read b
echo 'enter third number:'
read c
if test $a -gt $b -a $a -gt $c
then
echo $a is the largest
elif [ $b -gt $c ]
then
echo $b is the largest
else
echo "$c is the largest"
fi
Page 18 of 20
(B)
a=$1
b=$2
c=$3
if test $a -gt $b -a $a -gt $c
then
echo $a is the largest
elif [ $b -gt $c ]
then
echo $b is the largest
else
echo $c is the largest
fi
ex 8:
echo 'enter radius :'
read radius
if test $radius -gt 5
then
echo area is : `expr $radius \* $radius \* 3`
echo circumference is : `expr 2 \* 3 \* $radius`
else
echo 'enter radius greater than 5'
fi
Page 19 of 20
A2:
if [ $# -eq 0 ]
then
echo "You must supply a value"
else
if [ $1 -lt 0 -o $2 -lt 0 -o $3 -lt 0 ]
then
echo "Supply Positive Numbers"
elif [ `expr $1 + $2` -gt $3 -a `expr $1 - $2` -lt $3 -a `expr $1 + $3` -gt $2 -a
`expr $1 - $3` -lt $2 -a `expr $2 + $3` -gt $1 -a `expr $2 - $3` -lt $1 ]
then
echo "Valid Triangle"
echo "Perimeter = `expr $1 + $2 + $3`"
if [ $1 -eq $2 -a $1 -eq $3 ]
then
echo "Equilateral Triangle"
elif [ $1 -eq $2 -o $1 -eq $3 -o $2 -eq $3 ]
then
echo "Isosceles Triangle"
else
echo "Scalene Triangle"
fi
else
echo 'invalid values'
fi
fi
Page 20 of 20