0% found this document useful (0 votes)
9 views16 pages

Shell Program Unit 4

A shell script is a file containing a series of commands for the shell to execute, commonly used for automating repetitive tasks, ensuring reliability, and linking commands together. Shell scripts are natively supported on Unix/Linux systems and are lightweight, making them ideal for IT and DevOps tasks. They can include variables, conditional statements, and loops to perform complex operations efficiently.

Uploaded by

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

Shell Program Unit 4

A shell script is a file containing a series of commands for the shell to execute, commonly used for automating repetitive tasks, ensuring reliability, and linking commands together. Shell scripts are natively supported on Unix/Linux systems and are lightweight, making them ideal for IT and DevOps tasks. They can include variables, conditional statements, and loops to perform complex operations efficiently.

Uploaded by

dhanudhanuja8220
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Shell Script?

A shell script is a file containing a series of commands for the shell to execute. The shell itself
is a command-line interpreter (CLI), while a shell script is a saved list of instructions (usually
with .sh extension) like [Link].

Uses of Shell Scripts:

Here are the main reasons shell scripts are widely used in IT and DevOps:

1. Automate Repetitive Tasks


Shell scripts turn routine jobs like file cleanup, backups, or server updates into one-click
actions, saving time and reducing manual effort

2. Reliable and Consistent


Shell scripts run the exact same steps every time, without mistakes. Once you write and test a
script, you can count on it to perform tasks consistently whether it's setting up servers, cleaning
up files, or running a deployment. This removes human error and ensures predictable results.

3. Native Support on Unix/Linux Systems


Shell scripting is natively supported on Unix-based systems, requiring no additional
installations. The shell environment (like Bash or Zsh) is pre-installed, allowing scripts to run
seamlessly across most Linux distributions and Unix-like operating systems.

4. Great for Linking Commands to Work Together


Shell scripts make it easy to link different commands together. You can pass the output of one
command into another, filter data, or run tasks step by step all in one script. This helps
automate complex jobs using simple building blocks.

5. Ideal for IT, DevOps & Monitoring


Shell scripts help automate important tasks like checking system health, setting up servers, and
scheduling jobs to run at specific times (using tools like cron). In DevOps, they are widely
used to speed up deployments and manage infrastructure without doing everything manually.

6. Lightweight and Easy to Write


They are interpreted, so there is no compile step. You can write a useful script in minutes, and
test it instantly perfect for quick fixes and small tasks.

Understanding Shell Scripts: Structure, Syntax, and Usage:

Shells are interactive, meaning they take user input and execute commands. But typing
multiple commands repeatedly is inefficient.
Instead, you can store commands in a file a shell script and run them when needed. These
scripts are similar to Windows batch files and typically have a .sh extension.
If you are familiar with languages like Python or C, you will find shell scripting easy to grasp.
A shell script includes:

 Shell Keywords: if, else, break, etc.


 Shell Commands: cd, ls, echo, pwd, touch, etc.
 Functions
 Control Flow: if..then..else, case, loops, etc.

When to Use Shell Scripts


Shell scripts are useful when:
 Tasks are repetitive and manual.
 A sequence of commands needs to be executed.
 Automating system administration tasks (backups, updates).
 Processing files (renaming, moving, copying).
 Running batch jobs (compilation, deployment).
 Performing data processing (text filtering, sorting).
Not suitable when:
 Complex GUIs are needed.
 Performance-intensive tasks (better use C/C++/Python).
The First Shell Script:
The first shell script typically refers to a basic script designed to introduce fundamental concepts
of shell scripting, such as the shebang line, simple commands, and making the script executable.
Creating the First Shell Script:
 Create a file:
Open a text editor and create a new file, for example, [Link]. The .sh extension is conventional
for shell scripts but not strictly required for execution.
 Add the shebang:
The first line of the script must be the "shebang" (#!), followed by the path to the interpreter that
will execute the script. For a Bash script, this is commonly #!/bin/bash.
Code
#!/bin/bash
 Add commands: Include the commands you want the script to execute. A common first
command is echo, which prints text to the terminal.
Code
#!/bin/bash
echo "Hello, Shell Script!"
 Save the file: Save the file with the chosen name (e.g., [Link]).
Making the Script Executable and Running It:
 Change permissions: By default, newly created files may not have execute permissions. Use
the chmod command to add execute permission for the user:
Code
chmod +x [Link]
 Execute the script: Run the script from the terminal using ./ followed by the script's name:
Code
./[Link]
This will output "Hello, Shell Script!" to the terminal, demonstrating the successful execution of
your first shell script.

Steps to create a shell script:


1. Open a terminal and a text editor (like nano, vi, or gedit).
2. Create a new file:
bash
CopyEdit
nano [Link]
3. Write the script:
bash
CopyEdit
#!/bin/bash
echo "Hello, world!"
4. Save and exit.
5. Make it executable:
bash
CopyEdit
chmod +x [Link]
6. Run it:
bash
CopyEdit
./[Link]
📌 #!/bin/bash is the shebang that tells the system to use the Bash shell to run the script.
Interactive Shell Scripts:
An interactive shell script is a script that prompts the user for input during its execution and then
uses that input to influence its behavior. This allows for dynamic and user-driven interactions.
Here is a basic example of an interactive shell script that asks for the user's name and then greets
them:
These scripts interact with the user, asking for input and reacting accordingly.
Example:
bash
CopyEdit
#!/bin/bash
echo "What is your name?"
read name
echo "Hello, $name!"
📌 read command is used to accept user input.
Explanation of the script:
 #!/bin/bash: This is called a "shebang" and specifies that the script should be executed using the
Bash interpreter.
 echo "Please enter your name:": This command displays a message on the terminal, prompting
the user for input.
 read name: This command reads a line of input from the user and stores it in a variable
named name.
 echo "Hello, $name! Welcome to the interactive script.": This command displays a personalized
greeting, incorporating the value stored in the name variable.
Shell Variables
Variables store data like strings or numbers.
A shell variable is a character string in a shell that stores some value. It could be an integer,
filename, string, or some shell command itself. Basically, it is a pointer to the actual data
stored in memory. We have a few rules that have to be followed while writing variables in the
script (which will be discussed in the article). Overall knowing the shell variable scripting
leads us to write strong and good shell scripts.
Rules for variable definition
A variable name could contain any alphabet (a-z, A-Z), any digits (0-9), and an underscore
( _ ). However, a variable name must start with an alphabet or underscore. It can never start
with a number. Following are some examples of valid and invalid variable names:
 Valid Variable Names
ABC
_AV_3
AV232

 Invalid variable names


2_AN
!ABD
$ABC
&QAID

Note: It must be noted that no other special character except underscore can be used in a
variable name because all other special characters have special meanings in Shell Scripting.

Defining Variables

Syntax
variable_name = <variable data>

Example
num="1"
name="Devil"
These kinds of variables are scalar variables as they could hold one value at a time.

1) Accessing variable

Variable data could be accessed by appending the variable name with '$' as follows:
#!/bin/bash

VAR_1="Devil"
VAR_2="OWL"

echo "$VAR_1$VAR_2"

Output:
DevilOWL

2) Unsetting Variables

The unset command directs a shell to delete a variable and its stored data from list of variables.
It can be used as follows:
#!/bin/bash

var1="Devil"
var2=23
echo $var1 $var2

unset var1

echo $var1 $var2


Output:
DEVIL 23
23
Note: The unset command could not be used to unset read-only variables.

3) Read only Variables.

These variables are read only i.e., their values could not be modified later in the script.
Following is an example:
#!/bin/bash
var1="Devil"
var2=23
readonly var1
echo $var1 $var2
var1=23
echo $var1 $var2

Output:
Devil 23
./bash1: line 8: var1: readonly variable
Devil 23
Variable Types:

We can discuss three main types of variables:


1) Local Variable:
Variables which are specific to the current instance of shell. They are basically used within the
shell, but not available for the program or other shells that are started from within the current
shell.
For example:
`name=Jayesh`
In this case the local variable is (name) with the value of Jayesh. Local variables is temporary
storage of data within a shell script.

2) Environment Variable:
These variables are commonly used to configure the behavior script and programs that are run
by shell. Environment variables are only created once, after which they can be used by any
user.
For example:
`export PATH=/usr/local/bin:$PATH` would add `/usr/local/bin` to the beginning of the shell's
search path for executable programs.

3) Shell Variables:

Variables that are set by shell itself and help shell to work with functions correctly. It contains
both, which means it has both, some variables are Environment variable, and some are Local
Variables.
For example:
`$PWD` = Stores working directory
`$HOME` = Stores user's home directory
`$SHELL` = Stores the path to the shell program that is being used.
Shell Keywords
These are reserved words that have special meaning in shell.
Examples:
 if, then, else, fi
 do, done
 for, while, case, esac
 break, continue, function
📌 Cannot be used as variable names.
Another way of assigning values to variables in shell script:
While the direct assignment using the = operator (e.g., VAR="value") is the primary and most
common way to assign values to variables in shell scripts, several other methods exist for
specific scenarios: command substitution.
This allows the output of a command to be assigned to a variable.
Code
MY_DATE=$(date)
FILE_COUNT=$(ls -l | wc -l)
Reading User Input.
The read command allows you to prompt the user for input and store it in a variable.
Code
echo "Enter your name:"
read USER_NAME
Parameter Expansion with Default Values.
You can assign a default value to a variable if it's unset or null using parameter expansion.
Code
# Assigns "default_value" if MY_VAR is unset or null
MY_VAR=${MY_VAR:-"default_value"}

Assigning from Another Variable:


The value of one variable can be assigned to another.
Code
SOURCE_VAR="original"
DEST_VAR=$SOURCE_VAR
Arithmetic Expansion.
Assign the result of an arithmetic expression to a variable.
Code
NUM1=10
NUM2=5
SUM=$((NUM1 + NUM2))
declare -n (Nameref Variables in Bash).
This creates a "nameref" variable, which acts as a symbolic link or alias to another
variable. Changes to the nameref variable directly affect the linked variable.
Code
ORIGINAL_VAR="Hello"
declare -n ALIAS_VAR=ORIGINAL_VAR
ALIAS_VAR="World"
echo "$ORIGINAL_VAR" # Output: World

Conditional Statements:

There are total 5 conditional statements which can be used in bash programming
1. if statement
2. if-else statement
3. if..elif..else..fi statement (Else If ladder)
4. if..then..else..if..then..fi..fi..(Nested if)
5. switch statement

Their description with syntax is as follows: if statement This block will process if specified
condition is true.

Syntax:

if [ expression ]
then
statement
fi
if-else statement If specified condition is not true in if part then else part will be execute. Syntax

if [ expression ]
then
statement1
else
statement2
fi

if..elif..else..fi statement (Else If ladder) To use multiple conditions in one if-else block, then
elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this
process continues. If none of the condition is true then it processes else part. Syntax

if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi

if..then..else..if..then..fi..fi..(Nested if) Nested if-else block can be used when, one condition is
satisfies then it again checks another condition. In the syntax, if expression1 is false then it
processes else part, and again expression2 will be check. Syntax:

if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi

switch statement case statement works as a switch statement if specified value match with the
pattern then it will execute a block of that particular pattern When a match is found all of the
associated statements until the double semicolon (;;) is executed. A case will be terminated when
the last command is executed. If there is no match, the exit status of the case is zero. Syntax:

case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
esac
Example Programs Example 1: Implementing if statement

#Initializing two variables


a=10
b=20

#Check whether they are equal


if [ $a == $b ]
then
echo "a is equal to b"
fi

#Check whether they are not equal


if [ $a != $b ]
then
echo "a is not equal to b"
fi
Output

$bash -f [Link]
a is not equal to b
Example 2: Implementing [Link] statement

#Initializing two variables


a=20
b=20

if [ $a == $b ]
then
#If they are equal then print this
echo "a is equal to b"
else
#else print this
echo "a is not equal to b"
fi
Output

$bash -f [Link]
a is equal to b
Example 3: Implementing switch statement

CARS="bmw"

#Pass the variable in string


case "$CARS" in
#case 1
"mercedes") echo "Headquarters - Affalterbach, Germany" ;;

#case 2
"audi") echo "Headquarters - Ingolstadt, Germany" ;;

#case 3
"bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;
esac
Output

$bash -f [Link]
Headquarters - Chennai, Tamil Nadu, India.
Logical Operators :

They are also known as boolean operators. These are used to perform logical operations. They
are of 3 types:
 Logical AND (&&): This is a binary operator, which returns true if both the operands are
true otherwise returns false.
 Logical OR (||): This is a binary operator, which returns true if either of the operands is true
or if both the operands are true. It returns false only if both operands are false.

 Not Equal to (!): This is a unary operator which returns true if the operand is false and
returns false if the operand is true.
#!/bin/bash

#reading data from the user


read -p 'Enter a : ' a
read -p 'Enter b : ' b

if(($a == "true" & $b == "true" ))


then
echo Both are true.
else
echo Both are not true.
fi

if(($a == "true" || $b == "true" ))


then
echo Atleast one of them is true.
else
echo None of them is true.
fi

if(( ! $a == "true" ))
then
echo "a" was initially false.
else
echo "a" was initially true.
fi
Output:

Looping Statements
Looping Statements in Shell Scripting: There are total 3 looping statements that can be used
in bash programming

 `while` statement in Shell Script in Linux


 `for` statement in Shell Script in Linux
 `until` statement in Shell Script in Linux
 Examples of Looping Statements
To alter the flow of loop statements, two commands are used they are,
1. break
2. continue
Their descriptions and syntax are as follows:

`while` statement in Shell Script in Linux

Here the command is evaluated and based on the resulting loop will execute, if the command is
raised to false then the loop will be terminated that.
#/bin/bash
while <condition>
do
<command 1>
<command 2>
<etc>
done

Example:
#/bin/bash
a=0
# lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:

`for` statement in Shell Script in Linux


The for loop operates on lists of items. It repeats a set of commands for every item in a list.
Here var is the name of a variable and word1 to wordN are sequences of characters separated
by spaces (words). Each time the for loop executes, the value of the variable var is set to the
next word in the list of words, word1 to wordN.

Syntax:
#/bin/bash
for <var> in <value1 value2 ... valuen>
do
<command 1>
<command 2>
<etc>
done

Implementation of `for` Loop with `break` statement in Shell Script.

Example:

#/bin/bash
#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done
Output:

`until` statement in Shell Script in Linux


The until loop is executed as many times as the condition/command evaluates to false. The loop
terminates when the condition/command becomes true.
Syntax:
#/bin/bash
until <condition>
do
<command 1>
<command 2>
<etc>
done

Example:

#/bin/bash
a=0
# -gt is greater than operator
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:

The break Statement


The break statement is used to terminate the entire loop immediately. When break is
encountered, the loop is exited, and the script continues execution from the statement following
the loop. Syntax.
Code
break
Example:
bash
CopyEdit
for i in 1 2 3 4 5
do
if [ $i -eq 3 ]
then
break
fi
echo "Number $i"
done
Output:
javascript
CopyEdit
Number 1
Number 2
The continue Statement
The continue statement is used to skip the current iteration of a loop and proceed to the next
iteration. When continue is encountered, the remaining commands within the current iteration of
the loop are skipped, and the loop proceeds to evaluate the condition for the next
iteration. Syntax.
Code
continue
Example:
bash
CopyEdit
for i in 1 2 3 4 5
do
if [ $i -eq 3 ]
then
continue
fi
echo "Number $i"
done
Output:
javascript
CopyEdit
Number 1
Number 2
Number 4
Number 5

You might also like