0% found this document useful (0 votes)
11 views

Linux Chap-14

Linux

Uploaded by

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

Linux Chap-14

Linux

Uploaded by

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

UNIT – V

Chapter – 14
Introducing Bash Shell Scripting

WHAT IS SHELL SCRIPT?


It’s a sequence of commands written in text file which can be used in future
for execution.

Elements of a Good Shell Script


Following care has to be taken while writing the shell scripts:
 Has a unique name
 Includes the shebang (#!) to tell the shell which subshell should execute
the script
 Includes comments—lots of comments
 Uses the exit command to tell the shell executing the script that it has
executed successfully
 Is executable
Also take care that shell script name does not exist in advance while saving
any one of it. And don’t give the name of reserved keyword for naming the shell
script.

To check whether the script name exists or not, one can use ‘which’
command.
For eg:

EXECUTING THE SHELL SCRIPT


Follow the steps to execute shell script:
1. Create the sample script as shown below :
# gedit test.sh
2. Changing the permission of file :
If not done then it will show permission denied error as shown below:

To change permission use chmod command:

To execute shell script follow the steps:


Method 1

Method 2

WORKING WITH VARIABLES AND INPUT


A variable is a value which keeps on changing depending on the requirement
as it depends mostly on the circumstances.

Understanding Variables
Defining a variable in shell script as simple as like in other programming
language using varname=value and to get the value of a variable later on whose
value can be printed using ‘echo’ command.
The advantage of using variables in shell scripts is that you can use them in
different ways to treat dynamic data.

VARIABLES, SUBSHELLS, AND SOURCING


When a variable is defined then its scope is limited for the current shell only
ie if we start another shell (subshell) then the variable value will not be valid
in the sub shell. And also if we define variable in a subshell and if we quit the
subshell then the variable defined in the subshell will be not used in the parent
shell.
It is illustrated in the following example:

In the above example, variable values of ‘x’ and ‘y’ can be printed/echoed
before going into subshell using ‘bash’ command and as we see once we
enter subshell then values of ‘x’ and ‘y’ are not available.
And once we come out of the subshell using ‘exit’ command, those variable
values again becomes available for use.
Also in the above example if we see then the variable values declared in the
subshell are not acessible once we exit subshell and come back to parent shell.
But sometimes we want a variable to be used globally throughout the shells
which can be done by using the ‘export’ keyword before name of the varible.
Eg. If value of a variable ‘x’ is to be used globally then it has to be declared as
export x = 10. Here the value of x will remain same as 10 until the machine is
rebooted and it reamins available in all the subshells defined after it.

But if a variable is declared global inside the subshell then its value will be
available globally for all the consequent subshells defined after it but once the
subshell where the variable was declared is exited then the value of the variable
will be unavailable for the parent shell.
Another way of defining variables is by putting all the values of variables in a
single file which makes it easily available. The main advantage of putting all
variables in one file is that you can also make them available in other shells by
sourcing them. To do this we would use ‘. filename’ command considering the
name of the file of variables is filename.

WORKING WITH SCRIPT ARGUMENTS


Using Script Arguments
When running a script, you can specify arguments to the script on the command
line. While giving the command line arguments we need to remember that the
first argument is denoted by $0 which is the name of the script file itself and the
values which we want to pass for processing will be accepted from $1 for
the user defined first argument, $2 for second argument and so on till $9.

Counting the Number of Script Arguments


To count the number of arguments provided with a script, you can use $#.
Basically, $# is a counter that just shows you the exact number of arguments
used when running a script.
Following example illustrates the counting of arguments during execution:

Output of the above code is:


Referring to All Script Arguments

In the above example we have seen that the numbers of arguments are fixed.
But what about if the number of arguments are unknown?
To solve this problem we use ‘$@’ or ‘$*’
Difference between the above two is that $@ refers to a collection of all
arguments that is treated as all individual elements. $* also refers to a collection
of all arguments, but it cannot distinguish between the individual arguments that
are used. The following shell script displays the list of arguments passed during
the execution of the program:

Output:

From the output it can be seen that there is no difference in it. But actually
there is difference in the two outputs: the collection of arguments in $* is seen
as one text string and the collection of arguments in $@ is seen as separate
strings.
ASKING FOR INPUT
We can take the input from the user by simply asking them for it by using
‘read’ in the script. This will ask the user for an input and put that value into a
variable.

As you can see in example, we have taken a variable called ‘input’ for taking
user from input and while executing the code, Linux kernel waits for user to
enter the input and when user enters the input. Here ‘-e’ option is used to
interpret the meaning of ‘\t’ in the echo statement which means to leave a space
of ‘Tab’ (ie 8 character spaces). Similarly ‘-e’ option is used to interpret the
following:

USING COMMAND SUBSTITUTION


Variable text can be put in a script by using command substitution. This can
be achieved by putting the result of a command in the script which will be
helpful if the script has something to do with the result of a command. For using
command substitution, the command which we want to use has to be put
between back quotes or back ticks. Or we can write the command substitution
between braces with a $ sign in front of ‘circular bracket’ ie ‘(‘.

For eg: The following command displays the date in the said order using
command substitution.

Here date command is used with some of its special formatting characters by
specifying date to present result in the day-month-year format. Here command
is executed but the result of this can be placed in a variable which allows it to be
used later whenever needed in the script for performing calculations.

For eg. Here the following code shows how it can be done:

Here it can be seen that the command can be put in between the brackets i.e.
between $( and ) or in between the back ticks where it gives the same result.

Substitution Operators
It is compulsory to check that a variable has been assigned a value within the
script before it starts executing.

For this bash offers substitution operators as it assigns a default value if a


variable have not been initialised or assigned value etc.
CHANGING VARIABLE CONTENT WITH PATTERN MATCHING
A pattern-matching operator can be used to search for a pattern in a variable
and, if that pattern is found, modify the variable.
Pattern-matching operators allow you to remove part of a variable
automatically.

Code :

Output:

In the above example it is seen that the pattern-matching operator searches


for a / preceded by another character *. In this pattern-matching operator, ## is
used to search for the longest match of the provided string starting from the
beginning of the string. So, the pattern-matching operator searches for the last /
that occurs in the string and removes it and everything that precedes it.
But if we use only one ‘#’ to search then only the first ‘/’ will be eliminated
from the path and rest will be printed instead of the last directory.

Searching can be done from the end of the file as well and to do this we ‘%’
symbol is used instead of ‘#’. Single ‘%’ symbol means referring to the shortest
of the pattern whereas ‘%%’ symbol means longest match of the pattern.

PERFORMING CALCULATIONS
Bash offers some options that allow you to perform calculations from scripts.
For example, you can use bash calculation options to execute a command a
number of times or to make sure that a counter is incremented when a command
executes successfully.
USING CONTROL STRUCTURES
The execution of commands can be made conditional in shell scripts by
implementing technique known as flow control. bash offers many options to use
flow control in scripts.
if : This is used to execute the sentences if certain conditions are met. Also
we can mention what would happen if conditions dint meet.
case : This is used to handle multiple options given for executing only one
out of them when the condition is met.
for : This is used to execute the sentence certain number of times or we can
say to execute in loop.
while : Use while as long as the specified condition is met. For example, this
construction can be very useful to check whether a certain host is reachable or
to monitor the activity of a process.
until : This is the opposite of while. Use until to run a command until a
certain condition is met.

USING IF...THEN...ELSE
You can use it to find out whether a file exists, whether a variable currently
has a value, and much more.
The basic construction is if condition then command fi. Therefore, we can use
it to check one specific condition, and if it is true, a command is executed. Also
it can extend the code to handle all cases where the condition was not met by
also including an else statement.

Syntax :
if [ conditional expression ]
then
statement1
statement2
.
fi
This if statement is also called as simple if statement. If the given conditional
expression is true, it enters and executes the statements enclosed between the
keywords “then” and “fi”. If the given expression returns zero, then consequent
statement list is executed.
In this example, variable ‘cnt’ is initialised to value 100 and using if condition
value of variable ‘cnt’ is compared with 100 and since the value is same it
executes the ‘echo’ statement.

if [ conditional expression ]
then
statement1
statement2
.
else
statement3
statement4
.
fi
If the conditional expression is true, it executes the statement1 and 2. If the
conditional expression returns zero, it jumps to else part, and executes the
statement3 and 4. After the execution of if/else part, execution resume with the
consequent statements.
When using case, make it a habit to handle all options to accommodate the
unexpected. Ideally, when the script is run, the user will enter something that
you expect. But what if the user enters something unexpected? In that case, you
probably want the user to see some result or message. This is handled by the *)
at the end of the script.

USING WHILE
You can use while to run a command as long as a condition is true.
Syntax:
while [condition]
do
statements
.
done
USING FOR
Sometimes it’s necessary to execute a series of commands, either for a limited
number of times or for an unlimited number of times. In such cases, for loops
offer an excellent solution.
#!/bin/bash
# counter
# counter that counts from 1 to 9
for (( counter=1; counter<10; counter++ )); do
echo "The counter is now set to $counter"
done
exit 0
The conditional loop determines that, as long as the counter has a value
between 1 and 10, the variable counter must be automatically incremented by 1.

To do this, the construction counter++ is used. As long as the incrementing of


the variable counter continues, the commands between do and done are
executed.
When the specifi ed number is reached, the loop is exited, the script terminates,

and it indicates to the system with exit 0 that it has completed its work
successfully.

You might also like