Lab Sheet 2
Lab Sheet 2
We have seen from Lab00 that ls l gives files in long listing format as
shown in Figure below.
The listing includes the total block size (1 block=1024 bytes of memory) of
the files in the directory and subdirectories, type of permissions, owner,
group, size, date and time of last modification and the names of the files or
directories in the current directory.
First column of list identifies the type and permissions associated with each
file. Type is identified by first character; it is hyphen (-) for files and d for
directories. Following the type, a series of 9 characters that can take the
values r (read), w (write), x (execute), - tells about file permissions for
three types of users given below respectively.
Note: A hyphen in any position means that you dont have that particular
permission.
The chmod command is used to set the three permissions for all three
categories of users (owner, group and others) for the file. Only owner of the
file can set the access permissions.
Syntax:
chmod [OPTION]...MODE[,MODE]...FILE...
Examples:
Command Explanation
chmod u+x will Execute permission is added to the owner for the
file will
chmod ugo+x will or Execute permission is added to all for the file will
chmod a+x will
chmod o-x will Execute permission is removed from the others for
the file will
chmod g+rx, o+x will Read and execute permission to group and
execute permission to others for the file will
Alternative way to set the file permissions by using numbers:
Command Explanation
chmod 777 will Read, write and execute permissions to all for the file
will
chmod 774 will Owner and group have all three permissions and
others have only read permission for the file will
chmod 400 will Read permission to the owner for the file will is set.
Group and others dont have any access to the file.
2. 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.
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 file [ args ... ] e.g. sh firstShellPgm
sh calls the shell to read commands from file. Such a file is called a
command procedure or shell procedure or shell script.
Execute the program by typing
sh firstShellPgm
Arguments may be supplied with the call and are referred to in file using the
positional parameters $1, $2,...
then
sh secondShellPgm CP1SEC3 first
produces the result as shown in Figure 2.
When the file executes, the first argument (CP1SEC3 in the previous
example) replaces $1, second argument replaces $2 and so on.
So
echo The parameter1 is $1 and Parameter 2 is $2
is equivalent to
echo The parameter1 is CP1SEC3 and Parameter 2 is first
and
who|grep $1
is equivalent to
who|grep CP1SEC3
and
ls l $2*
is equivalent to
ls l first*
i.e. CP1SEC3 is assigned to variable 1 and first is assigned to variable 2
3. Interactive Shell Scripts
Interaction with the computer is always through input and output
operations. The read command allows the shell scripts to read input from
the user. Let us write our first interactive shell script here. You may save it
in the file first. The script is as follows
#this script asks user to input his name and then prints his name
echo What is your name?
read name
echo Hello $name. Happy Programming.
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.
5. Variables in Shell
To process our data/information, data must be kept in computers 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.
5.1 System Variables
Examples:
number=10 # this is ok
10=number # Error, Value must be on right side of the = sign.
vech=Bus # defines variable called 'vech' having value Bus
Rules for Naming variable name (Both UDV and System
Variable)
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
Try following in bc to clear your Idea and note 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 both bc and Linux Shell uses different ways to show True/False
values
6.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
If else statements are useful decision making statements which can be
used to select an option from a given set of options.
Unix Shell supports following forms of if..else statement:
if...fi statement
if...else...fi statement
if...elif...else...fi statement
Syntax:
test expression OR [ expression ]
Example:
Following script determine whether given argument number is positive.
if test $1 -gt 0 # if [ $1 gt 0 ] will also work
then
echo "$1 number is positive"
fi
Run it as follows
chmod +x ispostive
sh ispostive 5
5 number is positive
sh ispostive -45
Nothing is printed
sh ispostive
Test and justify the output
Detailed explanation
The line if test $1 -gt 0, test to see if first command line argument ($1)
is greater than 0. If it is true(0) then test will return 0 and output will printed
as 5 number is positive but for -45 argument 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: line 1: test: -gt: unary operator expected, is generated
by shell , to avoid such error we can test whether command line argument
is supplied or not.
test or [ expression ] works with
1.Integer ( Number without decimal point)
2.File types
3.Character strings
6.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:
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
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.
6.3 The case...esac Statement:
You can use multiple if...elif statements to perform a multiway branch.
However, this is not always the best solution, especially when all of the
branches depend on the value of a single variable. Unix Shell
supports case...esac statement which handles exactly this situation, and it
does so more efficiently than repeated if...elif statements.
Example: Shell Script to Simulate a Simple Calculator
Algorithm:
1. Start the program
2. Read a, b, op
3. Check for no. of inputs and if it is less than three exit the program
4. Use case statement for op
a. If op is + add a, b
b. If op is subtract a, b
c. If op is / divide a, b
d. If op is x multiply a, b
e. Else print error
5. Display the result
6. End the program
Program:
a=$1
op=$2
b=$3
if [ $# -lt 3 ]
then
echo "$0 num1 opr num2"
echo "opr can be +,-,/,x"
exit 1
fi
case "$op" in
+) echo $(( $a + $b ));;
-) echo $(( $a - $b ));;
/) echo $(( $a / $b ));;
x) echo $(( $a * $b ));;
*) echo "Error";;
esac
7. Exercises
7.1 Shell Script to swap values in two variables x and y
Algorithm:
1. Start the Program
2. Read the Value of X and Y
3. Using temporary variable Z interchange the values of X and Y
4. Display the result after Swapping
5. Stop the Program
Program:
echo -n "Enter Value for X:"
read x
echo -n "Enter Value for Y:"
read y
echo "Before Swap, X=$x and Y=$y"
z=$x
x=$y
y=$z
echo "After Swap, X=$x and Y=$y"
Algorithm:
1. Start the Program
2. Read Two Strings as Arguments
3. If Number of Arguments less than two exit the Program
4. Concatenate two strings and store the result
5. Using Length Function find the length of the result string
6. Display the Concatenated String with its length
7. Stop the Program
Program:
str1=$1
str2=$2
OUT="$str1$str2"
if [ $# -eq 0 ]
then
echo "$0 string1 string2"
exit 1
fi
len=$(expr length $OUT)
echo "Before Concatenation String1 is $str1 & String2 is $str2"
echo "Concatenated String is - $OUT"
echo "String Length is - $len"
7.3 Write a shell script that receives file name as argument checks if
every argument supplied is a file or a directory and reports
accordingly. Whenever the argument is a file, the number of lines on
it is also reported
Program:
if [ -f $1 ]
then
echo " $1 is a file "
echo " no of lines in the file are "
wc -l $1
elif [ -d $1 ]
then
echo " $1 is a directory "
else
echo " enter valid filename or directory name "
fi
----------------------------------------------------