3CS LSP Unit 4
3CS LSP Unit 4
What is Shell?: Shell is a UNIX term for an interface between a user and an operating system
service. Shell provides users with an interface and accepts human-readable commands into the
system and executes those commands which can run automatically and give the program’s
output in a shell script. An Operating is made of many components, but its two prime
components are –
Kernel
Shell
A Kernel is at the nucleus of a computer. It makes the communication between the hardware and
software possible. While the Kernel is the innermost part of an operating system, a shell is the
outermost one.
How to Write Shell Script in Linux/Unix: Shell Scripts are written using text editors. On your
Linux system, open a text editor program, open a new file to begin typing a shell script or shell
programming, then give the shell permission to execute your shell script and put your script at
the location from where the shell can find it. Let us understand the steps in creating a Shell
Script:
1. Create a file using a vi editor (or any other editor). Name script file with extension .sh
2. Start the script with #! /bin/sh
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh
“#!” is an operator called shebang which directs the script to the interpreter location. So, if we
use”#! /bin/sh” the script gets directed to the bourne-shell.
Types of Parameters
Variables: The variables which are a type of parameter are generally managed by the
users or the system. We can take an example of $var which is a variable parameter. The
system sets $var, but this variable parameter can be written by the user. So it’s not read-
only, like the special parameters.
Special Parameters: The special parameters are read-only which are maintained by the
shell. The special parameters are with a predefined meaning. Below are the various
special parameters:
Parameters Description
$# This parameter represents the total no of arguments passed to the script
$0 This parameter represents the script name
$n This parameter represents the arguments corresponding to a script when a
script is invoked.
$* This parameter describes the positional parameters to be distinct by space
$$ This parameter represents the process ID of a shell in which the execution is
taking place
$! This parameter represents the process number of the background that was
executed last
$@ This parameter is similar to the parameter $*
$? This parameter represents exit status of the last command that was executed.
Here 0 represents success and 1 represents failure
$_ This parameter represents the command which is being executed previously
$- This parameter will print the current options flags where the set command can
be used to modify the options flags.
Advantage of Shell Script Parameters: One of the main advantages of using the parameters is
that while passing the arguments to the function or a script, the code can be reused again and
again
Variables:
A variable is a character string to which we assign a value. The value assigned could be a
number, text, filename, device, or any other type of data.
A variable is nothing more than a pointer to the actual data. The shell enables you to create,
assign, and delete variables.
Variable Names: The name of a variable can contain only letters (a to z or A to Z), numbers
(0 to 9) or the underscore character (_). By convention, Unix shell variables will have their
names in UPPERCASE. The following examples are valid variable names −
_ALI
TOKEN_A
VAR_1
VAR_2
Following are the examples of invalid variable names −
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
Accessing Values: To access the value stored in a variable, prefix its name with the dollar
sign ($). For example, the following script will access the value of defined variable NAME
and print it on STDOUT −
#!/bin/sh
NAME="Zara Ali"
echo $NAME
The above script will produce the following value −
Zara Ali
Read-only Variables: Shell provides a way to mark variables as read-only by using the read-
only command. After a variable is marked read-only, its value cannot be changed. For
example, the following script generates an error while trying to change the value of NAME −
#!/bin/sh
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"
The above script will generate the following result −
/bin/sh: NAME: This variable is read only.
Unsetting Variables: Unsetting or deleting a variable directs the shell to remove the variable
from the list of variables that it tracks. Once you unset a variable, you cannot access the
stored value in the variable. Following is the syntax to unset a defined variable using the unset
command −
unset variable_name
The above command unsets the value of a defined variable. Here is a simple example that
demonstrates how the command works −
#!/bin/sh
NAME="Zara Ali"
unset NAME
echo $NAME
Types of variable: The shell is a command-line interpreter for Linux and Unix systems. It
provides an interface between the user and the kernel and executes commands. A sequence of
commands can be written in a file for execution in the shell. It is called shell scripting. It
helps to automate tasks in Linux. In shell scripting there are three main types of variables are
present. They are –
1. Local Variables
2. Global Variables or Environment Variables
3. Shell Variables or System Variables
1. Local Variable: A local variable is a special type of variable which has its scope only
within a specific function or block of code. Local variables can override the same variable
name in the larger scope. Let’s understand this concept using an example –
Shell script:
#!/bin/sh
getName(){
NAME=SATYAJIT #local variable
echo "$NAME (from function)" #valid if called using function
}
echo "$NAME - (outside function)" #invalid here
getName
3. Shell Variables: These are special types of 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 and to see all of them, we can use set / env / printenv command
Variable Name Description Usage
Holds the version of this
BASH_VERSION instance of bash. echo $BASH_VERSION
Provides a home directory of
HOME the current user. echo $HOME
HOSTNAME Provides computer name echo $HOSTNAME
USERNAME Provides username echo $USERNAME
White space removal: White spaces are invisible but take up the spaces. While executing the
command these white spaces are automatically removed from the output. Here, we'll
use echo command which is used to print the output that it receives from the shell.
Syntax:
echo <typedTtext>
Single and double quotes: If you want white spaces to be displayed then use them within the
quotes. You can use single as well as double quotes. Write argument within the quotes and print
it with 'echo' command. Linux 'echo' command will consider the whole data as a single argument
within the quotes.
Syntax:
echo < 'typedTtext' >
echo < "typedTtext" >
echo –e: Linux 'echo -e' command is used with '\n' and '\t' to start a new line and add a tab space
respectively. It works within single as well as double quotes.
Syntax
echo -e < 'typedTtext' >
echo -e < 'typedTtext" >
How to find out the exit code of a command: You need to use a particular shell variable called
$? to get the exit status of the previously executed command. To print $? variable use the echo
command or printf command:
date
echo $?
date-foo-bar
printf '%d\n' $?
Turn debugging information on or off: The '-x' option is used with the set command to show
command and their arguments. It is useful for debugging the shell script.
To turn on the debugging information:
set -x
To turn off the debugging information:
set +x
Disable Bash's default behavior: To disable the default behavior of Bash, execute the
command as follows:
set -C
Stop a script immediately: To stop a script immediately, execute the following command:
set -e
Getting Help: If you get stuck during the use of the set command, you can access the help
documentation from your terminal. To access the help manual, execute the below command:
set --help
Shift Command: Shift is a built-in command in bash which after getting executed, shifts/move
the command line arguments to one position left. The first argument is lost after using shift
command. This command takes only one integer as an argument.
Syntax:
shift n
Here, n is the number of positions by which you want to shift command-line arguments to the
left if you do not specify, the default value of n is assumed to be 1 i.e shift works the same as
shift 1.
Example: Let’s create a shell script file named as sampleshift.sh as follows. The total number
of command-line arguments is represented by $#. Use the following command to create the
desired shell script file
vi sampleshift.sh
Now paste the following code:
#!/bin/bash
# total number of command-line arguments
echo "Total arguments passed are: $#"
# $* is used to show the command line arguments
echo "The arguments are: $*"
echo "The First Argument is: $1"
shift 2
echo "The First Argument After Shift 2 is: $1"
shift
echo "The First Argument After Shift is: $1"
LOGICAL OPERATORS
We use the logical operators to test more than one condition. Following are the logical operators
that we will be discussing.
Operator Description
-a Logical AND
-o Logical OR
1. Logical AND: The logical AND -a operator will give true if both the operands are true.
Otherwise, false. Truth table of logical AND operator.
A B A -a B
2. Logical OR: The logical OR -o operator will give true if any one of the operand is true. If
both operands are false then it will return false. Truth table of logical OR operator.
A B A -o B
Example: The following is an example script that will prompt you to input a number and then
it checks whether the given number is even.
echo -n "Enter Number: "
read x
if [ $((x%2)) == 0 ]; then
echo "Number is Even"
fi
While Loop: A while loop is a statement that iterates over a block of code till the condition
specified is evaluated to false. We can use this statement or loop in our program when do not
know how many times the condition is going to evaluate to true before evaluating to false.
Syntax:
while [ condition ];
do
# statements
# commands
done
If the condition is true then the commands inside the while block are executed and are iterated
again after checking the condition. Also if the condition is false the statements inside the
while block are skipped and the statements after the while block are executed.
Example
#!/usr/bin/bash
a=7
while [ $a -gt 4 ];
do
echo $a
((a--))
done
echo "Out of the loop"
For Loop: There are a couple of ways to use for loops depending on the use case and the
problem it is trying to automate.
Simple For loop
Range-based for loop
Array iteration for loops
C-Styled for loops
Infinite for loop
1. Simple For loop: To execute a for loop we can write the following syntax:
Syntax:
#!/bin/usr/env bash
for n in a b c;
do
echo $n
done
2. Range-based for loop: We can use range-based for loops. In this type of loop, we can
specify the number to start, to stop, and to increment at every iteration (optional) in the
statement. There are two ways you can do this i.e. by mentioning the increment/decrementer
value and by incrementing by one by default.
Syntax:
#!/bin/usr/env bash
for n in {1..5};
do
echo $n
done
3. Array iteration for loops: We can iterate over arrays conveniently in bash using for loops
with a specific syntax. We can use the special variables in BASH i.e @ to access all the
elements in the array. Let’s look at the code:
Syntax:
#!/bin/usr/env bash
s=("football" "cricket" "hockey")
for n in ${s[@]};
do
echo $n
4. C-Styled for loops: As said earlier, we need to use the variables inside the for loops to
iterate over a range of elements. And thus, the C-styled for loops play a very important role.
Let’s see how we use them.
Syntax:
#!/bin/usr/env bash
n=7
for (( i=1 ; i<=$n ; i++ ));
do
echo $i
done
5. Infinite for loop: We don’t use this often but it is sometimes useful to get certain things
working. The syntax is quite easy and similar to the C-styled for loops.
Syntax:
#!/bin/usr/env bash
n=4
for (( ; ; ));
do
if [ $n -eq 9 ];then
break
fi
echo $n
((n=n+1))
done
Case Statement: Case statement in bash scripts is used when a decision has to be made
against multiple choices. In other words, it is useful when an expression has the possibility to
have multiple values. This methodology can be seen as a replacement for multiple if-
statements in a script.
Syntax:
case EXPRESSION in
Pattern_Case_1)
STATEMENTS
;;
Pattern_Case_1)
STATEMENTS
;;
Pattern_Case_N)
STATEMENTS
;;
*)
STATEMENTS
;;
Esac
Rules for case statement:
A case statement begins with the case keyword which is followed by
an expression and the in the keyword.
It ends with the esac keyword.
Multiple pattern cases can be used separated by | operator.
Closing parenthesis operator ‘)’ is used to end the pattern cases list.
A pattern case can contain special characters.
A pattern case and its body are termed as a clause.
Pattern case body must be followed by ;;.
In case an expression matches with two patterns cases then in such case the body
corresponding to the first matching pattern case that matches the expression is
executed.
Like C provides default keyword for default statement, likewise in the Bash case
statement, we can use the wildcard asterisk symbol (*) and define a final pattern case
to define the default case.
In case no pattern is matched, the return status is zero. Otherwise, the return status is
the exit status of the executed body of the matched pattern case.
FUNCTIONS
Functions enable you to break down the overall functionality of a script into smaller, logical
subsections, which can then be called upon to perform their individual tasks when needed. Using
functions to perform repetitive tasks is an excellent way to create code reuse. This is an
important part of modern object-oriented programming principles.
Pass Parameters to a Function: 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.
#!/bin/sh
# Define your function here
Hello ()
{
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali
Returning Values from Functions: If you execute an exit command from inside a function, its
effect is not only to terminate execution of the function but also of the shell program that called
the function. Based on the situation you can return any value from your function using
the return command whose syntax is as follows −
Syntax:
return code
Nested Functions: One of the more interesting features of functions is that they can call
themselves and also other functions. A function that calls itself is known as a recursive function.
Following example demonstrates nesting of two functions −
#!/bin/sh
# Calling one function from another
number_one ()
{
echo "This is the first function speaking..."
number_two
}
number_two ()
{
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
LINUX ALIASES
Linux 'alias' command replaces one string from the shell with another string. It is a shell built-in
command. It converts a complicated command into a simpler command or in other words, it
creates a shortcut by replacing it with the simpler one.
Making 'alias' in command line creates a temporary 'alias'. Temporary aliases are only available
until you exit the shell. To make permanent 'alias' store it in bash startup files.
Note: There will be no space on either side of (=) sign while typing 'alias' command. Quotes are
necessary if there are more than one word in the string being aliased.
alias syntax:
alias <newName>=<command> (To create alias for commands)
alias <newName>=<'command arg1 arg2....'> (To create alias for more than one argument)
alias <newName>=<'/home/sssit/path/...'> (To create alias by a path)
Creating an alias: Here, we are going to use following options for creating an alias.
1. Creating alias for 'file' command as 'fi'
2. Creating alias for 'ls-l' command as 'll'
3. Creating alias with two arguments
4. Creating alias for a path
How to remove alias: With the help of 'unalias' command you can remove created alias.
Syntax:
unalias <createdAlias>