Linux Notes Module 3
Linux Notes Module 3
Shell Programming
echo command in linux is used to display lines of text or string that are passed as an argument. This is a
built-in command that is mostly used in shell scripts and batch files to output status text to the screen or a
file.
Syntax :
echo [option] [string]
Options Description
-n do not print the trailing newline.
-e enable interpretation of backslash escapes.
\b backspace
\\ backslash
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
Examples:
1. $ echo Welcome //Output : Welcome
2. $ x=10
$ echo The value of variable x = $x //Output :The value of variable x = 10
3. $ echo -e “Welcome \nto \nLinux” //Output : Welcome
to
Linux
Shell Variables
What is a shell environment? (2 marks May 23)
A shell maintains an environment that includes a set of variables defined by the
login program, the system initialization file, and the user initialization files. In
addition, some variables are defined by default.
System Defined Shell Variables - These variables are pre-defined variables. They are
created and maintained by Linux Shell itself. These variables are required by the shell to
function properly. They are defined in Capital letters. Following are some system defined
shell variables.
1. PATH - Describes the directories that are to be searched whenever a command is
executed. A colon (:) separates one path from the next in the list.
eg: PATH = : / bin : / usr / bin : / usr /s4c
echo $ PATH
2. LOGNAME - Describes the login name
eg : echo $LOGIN
3. HOME - Describes the path of the user’s home directory.
eg: echo $ HOME
4. PWD - Stores present working directory
5. SHELL - Stores the path to the shell program that is being used.
Eg: SHELL = /bin/bash
6. MAIL - stores path to the current users mail box.
We can see them by using the command env. We can change our variable to environment variable by using
export command.
Rules for naming variables
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _).
1. Begin with alphanumeric characters or under score ( _ ) followed by one or more alphanumeric
characters.
2. Values are case sensitive.
3. Don’t use special characters.
Null variables can be defined as $v=““.
Don’t put space on either side of the equal ( = ) sign.
To access the value stored in a variable, prefix its name with the dollar sign ($)
Arithmetic operators
1. + - addition $a+$b
2. - - subtraction $a-$b
3. * - Multiplication $ a \* $ b
4. / - Division $a\/$b
5. % - remainder of Division
Relational Operators
1. – eq - Equals
2. – ne - not equal to
3. – gt - greater than
4. – ge - greater than or equal to
5. – lt - less than
6. – le - less than or equal to
Logical operators
1. – a - AND
2. – o - OR
Quotes: There are 3 types of quotes
1. “ - double quotes
2. ‘ - single quotes
3. ` - back quotes
Control Structures:
( Explain decision making and branching statements with examples. 15 marks May 23)
1. if - Simple if is used for decision making in shell script. If the given condition is true, then it will execute
the code inside the block.
Syntax:
if [ condition ]
then
statements
fi
eg: # Check number is 1
echo “ enter a number “
read no
if [ $ no – eq 1 ]
then
echo “ number 1”
fi
2. if … else - it is also used for decision making. If the condition is true, then it will execute the statements in the
true block; otherwise it will execute the false block.
Syntax:
if [ condition ]
then
statements
else
statements
fi
eg: # Check number is positive or not
echo “ enter a number “
read no
if [ $ no –gt 0 ]
then
echo “ number is positive “
else
echo “ number is negative “
fi
3. if … elif - It is possible to create compound conditional statements using els .. if (elif). If the 1st condition is true,
then the true part is executed. Otherwise, the 2nd condition is checked. If the 2nd condition is true, the true part of elif is
executed.
Syntax: if [ condition ]
then
statements
elif [ condition ]
then
statements
fi
eg: Check + ve or - ve
echo “ enter a number “
read n
if [ $ n –gt 0 ]
then
echo “ Positive “
elif [ $ n –lt 0 ]
then
echo “ Negarive “
fi
(Qn: Rating check)
4. If .. elif … else - if the condition1 is true, then the true block is executed. If the condition 2 is true, then the
true block of elif is to be executed. Otherwise the else block is to be executed.
Syntax: if [ condition1 ]
then
statements
elif [ condition 2 ]
then
statements
else
statements
fi
eg: Check + ve or - ve or 0
echo “ enter a number “
read n
if [ $ n –gt 0 ]
then
echo “ Positive “
elif [ $ n –lt 0 ]
then
echo “ Negarive “
else
echo “ zero “
fi
5. if – elif ladder - It is a series of if statements. Here each if is a part of the else clause of the previous if. Here
statements are executed based on the true condition. If none of the conditions is true then the else block is executed.
Syntax : if [ condition ]
then
statements
elif [ condition ]
then
statements
elif [ condition ]
then
statements
.
.
.
else
statements
fi
eg: print day name corresponding to day number
echo “ Enter a number between 1 and 7 “
read n
if [ $n – eq 1]
then
echo “ Sunday “
elif [ $n – eq 2 ]
then
echo “ Monday “
elif [ $n – eq 3 ]
then
echo “ Tuesday “
elif [ $n – eq 4 ]
then
echo “ Wednesday “
elif [ $n – eq 5 ]
then
echo “Thursday “
elif [ $n – eq 6 ]
then
echo “ Friday “
elif [ $n – eq 7 ]
then
echo “Saturday “
else
echo “ Not valid “
fi
6. Nested if statement : When an if statement contains many elif constructs then we say that it is a nested if statement.
Syntax:
if [ condition]
then
statements
else
if [ condition]
then
statements
fi
fi
eg: Check for user name and password
echo "Enter your Name"
read name
if [ $name = "Arun" ]
then
echo "Enter Password"
read pass
if [ $pass = "abcd" ]
then
echo "Hello $name"
else
echo "Wrong password"
fi
else
echo "wrong username"
fi
Eg 2: find the biggest among 3 numbers
eg: # Accept the day number of a week and display day name
echo “ Enter a number between 1 and 7 “
read n
case $n in
1 ) echo “Sunday “ ; ;
2 ) echo “Monday “ ; ;
3 ) echo “Tuesday “ ; ;
4 ) echo “Wednesday “ ; ;
5 ) echo “Thursday “ ; ;
6 ) echo “Friday “ ; ;
7 ) echo “Saturday “ ; ;
* ) echo “Invalid Day Number“ ; ;
esac
Read a character and display whether it is vowel or not
echo “ Enter a Character “
read c
case $c in
[ a e i o u A E I O U ] ) echo “ It is vowel “ ; ;
* ) echo “ Not a vowel “ ; ;
esac
Looping Statements
1. while - It is used to repeatedly execute a set of statements any number of times when a condition is true until the
condition evaluates to false..
Syntax : while [ condition ]
do
statements
done
eg: # write a shell script to display integers from 1 to 10
i =1
while [ $ i - le 10 ]
do
echo $ i
i = `expr $ i + 1 `
done
2. until - It is used to execute a set of commands repeatedly until a condition is true. It is an inversion of the while
loop. Syntax: until [ condition ]
do
statements
done
eg: # To display numbers from 1 to 10
i =1
until [ $ i - gt 10 ]
do
echo $ i
i = ‘ expr $ i + 1 ‘
done
3. for Syntax (1): for variable_name in list
do
statements
done
For each value in the list, the variable_name gets the value and the loop is executed.
This syntax is similar to the syntax of for statement in C++ language. expn1 is executed 1st for initialization. expn2 is
executed next for checking condition. If it is true, the loop is executed. Then expn3 is executed for incrementation or
decrementation of the loop control variable. Then the loop is repeated if expn 2 is evaluated to true, and so on.
eg: for ((i = 1 ; i < 10; i ++ ))
do
echo $ i
done
Control Statements used in looping statements
1. break - The break statement is used to terminate the execution of the loop and transfer the control
to the statement after the end of the loop.
Syntax 1): break
Used to exit from the loop
Syntax 2): break n
Used to exit from a nested loop. ‘n’ specifies the number of loops to be exited.
eg: a=0
while [ $a –lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a= ‘ expr $a + 1’
done
2. continue - It is used to transfer the control to the next iteration of the loop, ignoring the remaining
porttion of the current iteration.
Syntax 1): continue
Syntax 2): continue n
Here ‘ n ‘ specifies the nth enclosing loop to continue.
Eg: # to display odd numbers from a list
NUMS = “ 1 2 3 4 5 6 7 “
for NUM in NUMS
do
Q = ‘ expr $ NUM % 2 ‘
if [ $Q - eq 0 ]
then
continue
fi
echo $i
done
Question: Explain function in shell with suitable example. How will you pass parameters in shell?
Answer: A function is a block of code that carries out a certain activity. A function can be called and reused.
Syntax:
function_name ()
{
list of commands
}
Example :
Hello () {
echo "Hello World"
}
Save the script above in your Linux system as test.sh and then run it in the terminal by writing ./test.sh
You can define a function that will accept parameters while calling the function. These parameters
would be represented by $1, $2 and so on.
Following is an example where we pass two parameters Zara and Ali and then we capture and
print these parameters in the function.
Example :
# Define your function here
Hello () {
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali
Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Question: Write a shell script to copy all files with .c extension in the current working directory to a
subdirectory.
Answer : cp *.c /program
1st three lines define the variables that configure the environment.
● SHELL - Shell environment used for running jobs
● PATH - Path to execute the programs
● MAILTO -usernames of the users who receive the output of the anacrons jobs by email.
The next 2 variables modify the scheduled time for the defined jobs.
● RANDOM_DELAY – Maximum number of minutes that will be added to the delay. If the time is missed,
the scheduled jobs are not executed on the day.
The remaining lines are in the following format:-
● Period in days – Frequency of job execution in days.
● Delay in minutes – number of minutes to wait before executing the job.
● Job identifier – unique name of a particular job.
● Command - the command to be executed.
2. cron - Configuration files for cron jobs are in the etc/crontab, which can only be modified by the root user.
The file contains the following:
The 1st three lines contain the SHELL, PATH and MAILTO variables. In addition, the file can contain HOME
variable. The home variable defines the home directory. The remaining lines have the following format:-
Minute hour day month day of week user name command
Minute - integer from 0 -59
Hour - 0 – 23
Day - 1 – 31
Month - 1 – 12
Day of week - 0–7
User name - specifies the user
Command - commands to be executed
* can be used to specify all valid values.
Any line beginning with # are comments and are not processed.
To create a crontab, use the command:-
crontab –e : to edit
eg:
29 0 * * * / usr / bin /example
To run the command /usr / bin / example at 12.30 everyday.