0% found this document useful (0 votes)
17 views45 pages

I Am Sharing 'FC - MOD3 - Shell - Scripting-1' With You

Uploaded by

Xorus Dremus
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)
17 views45 pages

I Am Sharing 'FC - MOD3 - Shell - Scripting-1' With You

Uploaded by

Xorus Dremus
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/ 45

GXEST203- FOUNDATIONS OF

COMPUTING: FROM HARDWARE


ESSENTIAL TO WEB DESIGN
MODULE 3 S2 CSE
Shell Scripting
■ It is a method for automating tasks and executing a series of commands in a Unix/Linux
shell (or Windows command prompt).
■ It entails writing scripts using a shell language, such as Bash (Bourne Again SHell) in
Linux or PowerShell in Windows.
■ These scripts are useful for automating repetitive tasks, managing system operations,
and processing data.
Concepts
■ Shell: The shell is a command-line interface that allows users to interact with the
operating system. Common shells include Bash, Zsh, Ksh, and Fish on Linux/Unix
systems, and PowerShell on Windows.
■ Script :A shell script is a plain text file containing a series of commands that the shell
can execute. These commands are written in a scripting language (e.g., Bash,
PowerShell).
■ Shebang (#!): The shebang at the beginning of a shell script defines the interpreter to use
for executing the script.
For example,#!/bin/bash
-tells the system to use Bash to interpret the script.
Basic Structure
i) Shebang: Defines the interpreter.
ii) Commands: A series of shell commands.
iii) Variables: Used to store values (e.g., strings, numbers).
iv) Control Flow: Loops and conditionals.
v) Comments: Lines starting with # are comments.
■ Shell scripting is a valuable tool across several professions and fields due to its
flexibility, power, and widespread support of operating systems.
■ It is used to automate repetitive system tasks such as file backups, resource monitoring,
and use account management.
■ Developers often use shell scripting to automate development tasks, like automating file
manipulation ,deploying software to servers, running test suites, and more.
■ System administrators often use shell scripts for automating administrative tasks like
backups, system monitoring, user account creation and management, and many more
routine activities. This allows for efficiency, consistency, and accuracy.
Advantages
1. Automation of repetitive tasks.
2. Efficiency
3. Simplicity
4. Portability
5. Cost Effective
6. Powerful text processing
7. Scheduling and task management
8. Error handling and debugging
9. Integration with other tools
10. Customization and Flexibility
11. Cost of maintenance
12. No need of external software
13. System administration and monitoring
Disadvantages
■ Limited portability across different shells
■ Debugging can be difficult
■ Error handling limitations
■ Performance issues.
■ Security Concerns
■ Limited support for advanced data structure
■ Complexity for large projects
■ Poor error reporting
■ Limited libraries and framework
■ Hard to manage user input
Key Features
❑ Command-Line (CLI ) : Bash serves as an interactive shell that allows users to type
commands to interact with the operating system.
❑ Scripting Capabilities: Bash is often used to write shell commands, which can automate
repetitive tasks, system scripts. A shell script is a text file containing a series of
administration, and file management operations.
❑ Job Control: Bash supports job control, allowing users to run multiple processes in the
background, bring them to the foreground, and manage them using commands like fg,
bg.and jobs.
❑ Input and Output Redirection: Bash allows for input/output redirection, enabling the use
of file-based input/output and piping between commands. For example, using the >
operator to redirect output to a file or | to pipe output from one command to another.
■ Control Flow (Conditionals, Loops, Functions): Bash supports control structures such as
if, for, while, until, and case for creating conditional statements and loops. Functions can
also be defined and called to modularize scripts.
■ Variables and Environment Variables: Bash allows for the use of variables to store
values, which can be referenced in commands and scripts. Environment variables are
used to store system-wide settings like $PATH, which dictates where executable
programs are located.
■ Aliases: Bash supports creating aliases for frequently used commands or combinations
of commands, making it easier to execute complex commands with shorter names.
■ Tab Completion and History: Bash offers tab completion, where typing part of a
command or file name and pressing Tab will complete the rest. It also maintains a
history of commands entered, which can be navigated using the Up and Down arrow
keys.
Basic Commands
❖ echo: Displays a message or the value of a variable.
Eg: echo "Hello, World!“
❖ ls: Lists files and directories in the current directory.
ls
❖ cd: Changes the current working directory.
cd/path/to/directory
❖ pwd: Prints the current working directory.
pwd
❖ cp: Copies files or directories.
cp file1.txt file2.txt
❖ mv: Moves or renames files or directories.
my oldname.txt newname.txt
❖ rm: Removes files or directories.
rm file1.txt
❖ cat: Displays the contents of a file.
cat file1.txt
❖ touch: Creates a new empty file or updates the timestamp of an existing file.
touch newfile.txt
❖ man: Displays the manual or help page for a command.
man command
❖ find: Searches for files and directories.
find/path/to/search -name "filename“
❖ grep: Searches for text within files.
grep "pattern" filename.txt
❖ chmod: Changes file permissions.
chmod 755 script.sh
❖ sudo: Executes a command with superuser (root) privileges.
sudo apt-get update
Basics of Scripting
❑ Variables
• Storage locations that have a name. They are 'name-value' pairs.
• Syntax: variablename=“value”
E.g.: age=20
• Variable names can contain: LETTERS (a-z, A-Z),DIGITS (0-9), &,UNDERSCORES (_)
[ONLY!].VARIABLE NAMES CANNOT START WITH A DIGIT!
• After declaring and assigning values to variables, you can access them using a dollar symbol ($) followed by
the variable name.
AGE=25
echo $AGE
• Any variable whether it is written inside a function or outside a function by default is a global variable. If one
wants to make a local variable then she/he need to use the keyword "local".

NOTE: NO SPACES before or after the ‘=‘.


The variable names are CASE-SENSITIVE!.
❑ Input & output
• Input & output are fundamental concepts for shell scripting. A script can take one or
more inputs and can also produce zero or many outputs. It may even produce some
errors.
• Reading user input by using read command.
• Eg1) echo :Enter name:”
read name
echo “Entered name: $name”
2) Read name1 name2 name3
echo “Names: $name1, $name2, $name3
■ Read Flags:
❑ Functions
• A function is a block of code that performs some tasks and it can be called multiple
times for performing tasks.
• E.g.
#! /bin/bash
#It is a function
myFunction ()
{echo “hello”}
#function call
myFunction

Example2: greet() {
echo "Hello, $1!"
}
greet "Alice"
greet "Bob"
Variable Scopes

■ Every declared variable must have a scope, defining where in the program the variable
can be used.
■ Variable scopes in Bash can be defined in two ways
1. Global variable
2. Local variable:
➢ Bash Global Variables
■ Variables declared in a shell script are referred to as global variables.Global variables
can be accessed within a function or any nested blocks of a shell script file.
■ The default variable declared in a script file is called a global variable.
setAge() {
echo "Inside Function Age: $AGE"
}
AGE=40
setAge
echo "Script Age: $AGE“
■ Output
Inside Function Age: 40
Script Age: 40
Bash Local variables

■ Local variables are declared inside a block of code or a function. The scope of these
variables is visible only within the block where they are declared.
■ Syntax:
– local variablename=variablevalue
Eg: setAge() {
local AGE=25
echo "Local Variable Age: $AGE"
}
AGE=40
setAge
echo "Global Age: $AGE“

Output
Local Variable Age: 25
Global Age: 40
Operators
■ Operator is a symbol in programming that performs an operation on operands.The
operators are:
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) String Operators
5) File Test Operators
Arithmetic Operators
ADD TWO NUMBERS:
#! /bin/bash
# Calculate the sum of two integers with pre initialize values
# in a shell script

# Initialize two variables with number


a=10
b=20

# Calculate sum
sum=$(( $a + $b ))

# Display the result


echo "Sum is: $sum"
Calculate Sum with Run Time Input

Output
Relational Operators
Logical Operators
■ These operators are used to perform logical operations on variables/expressions/data.
➢ 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.
String Comparison Operators
Operator Description
== Returns true if the strings are equal
!= Returns true if the strings are not equal
-n Returns true if the string to be tested is
not null
-z Returns true if the string to be tested is
null
File Test Operators
Decision Making
■ Two types of decision-making statements are used within shell scripting.
■ They are: 1) if-else statement: if else statement is a conditional statement. It can be used to
execute two different codes based on whether the given condition is satisfied or not.
■ Different types are:
1) if-fi
2) if-else-fi
3) if-elif-else-fi
4) nested if-else
Syntax for If Conditional Statements:
if [ expression ]; then
statements
fi
e.g.:
If-Else Conditional Statements
■ The if-else conditional statements in Bash allow you to execute different code blocks depending on whether a
condition is true or false.
■ Syntax:
if [ condition ]; then
# Execute code block if the condition is true
else
# Execute code block if the condition is false
fi
Eg: #! /bin/sh
age = 25
if [ $age -gt 60 ]; then
echo "Senior Citizen"
else
echo "Not Senior Citizen"
fi
If..Elif..Else Statements
➢ Use if..elif..else conditional statements in Bash to execute different code blocks based on
multiple conditions.
➢ Syntax:
if [ condition1 ]; then
# Execute code if condition1 is true
elif [ condition2 ]; then
# Execute code if condition1 is false and condition2 is true
else
# Execute code if both condition1 and condition2 are false
fi
Example
age=25
if [ $age -gt 60 ]; then
echo "Senior Citizen"
elif [ $age -lt 14 ]; then
echo "Child"
else
echo "Adult"
fi
2) case-esac statement
• case-sac is basically working the same as switch statement in programming. Sometimes if we have to check
multiple conditions, then it may get complicated using if statements.
• Syntax:
case Expression in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
*) # Default case ;;
esac
Eg: Name="Shivanika"
case “$Name” in
#case 1
"Anika") echo "Profession: Software Engineer" ;;
#case 2
"Arnav") echo "Profession: Doctor" ;;
#case 3
"Shivanika") echo "Profession: Lawyer" ;;
esac
Loops
■ Loops are used to execute code block for a number of times.
■ for loop
■ Syntax:
for element in list; do
# Code block
done
❑ Example:
for i in 1 2 3 4 5; do
echo "Number: $i"
done
while loop
■ The while loop in Bash allows for the repeated execution of code as long as a specified
condition is true. If the condition becomes false, the loop exits.
■ Syntax:
while [ condition ]; do
# code block
done
❑ Example:
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
for index loop
■ for index loop is similar to C language for index loop It executes code multiple times based on condition
is true, It starts with initial value and iteration contails the value to be incremented by 1.
■ Syntax:
for (( assignment; condition; iteration )); do
# code block
done
❑ Example:
for (( i=0; i<5; i++ ));do
echo $i
done
Until loop
■ The until keyword in Bash is employed to repeatedly execute code until a specified condition
becomes true, at which point the loop exits.
■ Syntax:
until [ condition ]; do
# code block
done
❑ Example:
i=0
until [ i -eq 100 ];
do
echo "$i"
i=$(( i+1 ))
done
Writing Bash Scripts
■ To write a Bash Script, we should follow these steps:
• First, we should create a file with the .sh extension.
To create and write a file with the .sh extension we can use gedit text editor.
Syntax: gedit/nano scriptname.sh
• Next, we can write down the bash scripts within it.
The first line of the script file should be:
#! /bin/bash
This will tell the system to use Bash for execution.
Then we can write our own scripts.
■ After that, we can provide execution permission to it, after saving the file.
o To provide execution permission,
chmod +x scriptname.sh
o To execute the script, we can use:
./scriptname.sh
A basic Bash script is just a series of commands stored in a text file,which can be executed
in a terminal.
Simple bash script
#! /bin/bash
#This is a simple Bash script
echo "Hello, $USER!" # Display a greeting message

# List files in the current directory


echo "Files in the current directory:“
ls

# Check if a directory exists


if [ -d "/tmp" ]; then
echo "/tmp exists“
else
echo "/tmp does not exist“
fi
■ Shebang: The first line tells the system that this script should be run using Bash. It
specifies the path to the Bash interpreter (/bin/bash). It's a convention used to specify
which shell or interpreter should be used to execute the script.
■ Comment: Anything after the # is a comment in Bash. This line is just a description and
does not get executed. It's used for adding notes to the script for clarity.
■ echo Command: The echo command is used to print text to the terminal. Here, it prints
"Hello, $USER!".SUSER: This is a built-in environment variable that holds the current
user's username. When the script runs, it will greet the user by name.
■ Is Command: The Is command lists the contents of the current directory.
■ if Statement: This conditional statement checks whether a specific directory exists.
Working with Files
■ Check if a File Exists
file="test.txt"
if [ -e $file ]; then
echo "File exists."
else
echo "File does not exist."
fi
■ Read a File Line by Line
while read line; do
echo $line
done < test.txt
■ Write Output to a File
echo "This is a line of text" > output.txt
Debugging a Shell Script

■ Run a Script in Debug Mode


■ Use -x to debug a script:
bash -x script.sh
■ Example 1: Backup Files
#! /bin/bash
backup_dir="backup_$(date +%Y%m%d)"
mkdir -p $backup_dir
cp *.txt $backup_dir
echo "Backup completed. Files copied to $backup_dir“

■ Example 2: Disk Usage Alert


#! /bin/bash
threshold=80
usage=$(df / | grep / | awk '{print $5}' | sed 's/%//')
if [ $usage -gt $threshold ]; then
echo "Warning: Disk usage is above $threshold% ($usage%)"
else
echo "Disk usage is under control ($usage%)"
fi
Practice Exercises

■ Write a shell script to find the largest of two numbers.


■ Write a shell script to find the largest of three numbers.
■ Write a shell script to check whether given number is odd or even.
■ Write a shell script to find the sum of digits of a number.
■ Write a shell script to find the factorial of a number.
THANK YOU

You might also like