I’ve corrected the spelling, grammar, punctuation, and formatting while keeping your original wording, explanations, examples, and overall structure intact. I’ve also aligned the code examples and operators to make the notes easier to read and use.
Shell Scripting
We have used a lot of commands like ls, cd, pwd. Now, whenever we are automating something, we need all these commands in a single file so we can leverage them to do our tasks on their own.
Now, we have divided these things into three main categories:
- Shell: Basically acts as a command interface.
- Bash: This is an interpreter, you can say your terminal.
- Shell Script: This is the main file that we are trying to learn.
So, now it’s time to write some shell scripts so that we can run them in a Bash terminal.
The next thing is the extension. The extension we have for Bash files is .sh.
The echo command is used to print anything. Then we can use the bash or sh command to run a file, or we can use another mechanism by changing the permissions. We will learn that later.
1. Printing Output Using Echo
bash
echo "Welcome to Linux"
echo "Welcome to DevOps"
echo "Welcome to Shell Scripting"
We can use echo -n to print something without moving to the next line.
bash
echo -n "Hello "
echo "World"
2. Variables
To define a variable name, we use the following naming convention rules:
- It should not have any special characters other than underscores (
_). - It cannot start with a numeric value.
- It should not be a keyword.
- We can assign a value to any variable by giving the name as shown in the example below.
- Make sure you don’t add any spaces around the
=sign.
bash
variable_name=value
You can use the dollar symbol ($) inside echo to show the variable’s value.
bash
name="Rahul"
echo "My name is $name"
Adding a few more examples for the same:
bash
name="Rahul"
age=25
city="Jaipur"
echo "Name: $name"
echo "Age: $age"
echo "City: $city"
Taking User Input
We can use the read command to take input from the user.
bash
echo "Enter your name:"
read name
echo "Welcome $name"
We can also take multiple inputs in a single line.
bash
echo "Enter your first and last name:"
read firstname lastname
echo "Your name is $firstname $lastname"
Command Substitution
You can also use any command and store its output inside a variable. We will see this soon.
bash
current_date=$(date)
current_user=$(whoami)
hostname=$(hostname)
echo "Date: $current_date"
echo "User: $current_user"
echo "Hostname: $hostname"
Readonly Variables
We can use readonly to make a variable constant.
bash
readonly company="Google"
echo "Company: $company"
# This will produce an error
company="Microsoft"
More Variable Examples
bash
name="Linux"
echo "Operating System: $name"
num1=10
num2=20
echo "Number 1: $num1"
echo "Number 2: $num2"
echo "Addition: $((num1 + num2))"
Floating-Point Numbers
In Shell Scripting, there is only one number data type. For floating-point calculations, we can use the bc command.
We can pass the output of one command to another command to get the float value.
bash
num1=10.5
num2=5.5
result=$(echo "$num1 + $num2" | bc)
echo "Result: $result"
Arrays
Then we have arrays, and in here, arrays are used with small brackets, and you can use indexing, of course.
bash
fruits=("Apple" "Banana" "Mango")
echo "First Fruit: ${fruits[0]}"
echo "Second Fruit: ${fruits[1]}"
echo "All Fruits: ${fruits[@]}"
3. If-Else Statements
Something similar to what we use in other programming languages.
bash
is_active=true
if [ "$is_active" = "true" ]; then
echo "Service is active"
else
echo "Service is inactive"
fi
4. Escape Sequences
We can use escape sequences with echo -e.
bash
echo -e "Name:\tRahul"
echo -e "City:\tJaipur"
echo -e "Country:\tIndia"
5. Arithmetic Operators
We can perform mathematical operations using arithmetic operators.
bash
a=10
b=20
result=$((a + b))
echo "Addition: $result"
The following are the arithmetic operators available in Shell Scripting:
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
** | Power |
6. Comparison Operators
The following are the comparison operators available in Shell Scripting:
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-gt | Greater than |
-lt | Less than |
-ge | Greater than or equal |
-le | Less than or equal |
Example: Equal Operator
bash
a=10
b=10
if [ $a -eq $b ]; then
echo "Both are equal"
fi
Example: Combining Conditions
We can combine comparison operators using && (AND) and || (OR).
bash
age=25
if [ $age -gt 18 ] && [ $age -lt 60 ]; then
echo "Eligible"
fi
Example: NOT Operator
bash
status="inactive"
if [ ! "$status" = "active" ]; then
echo "Service is not active"
fi
Nested If-Else / If-Elif-Else
We can use nested if-else or if-elif-else statements in Shell Scripting.
bash
marks=75
if [ $marks -ge 90 ]; then
echo "Grade A"
elif [ $marks -ge 70 ]; then
echo "Grade B"
elif [ $marks -ge 50 ]; then
echo "Grade C"
else
echo "Fail"
fi
File and Directory Validation
There is one special operator, -f, that basically lets you validate whether a file exists or not.
bash
filename="test.txt"
if [ -f "$filename" ]; then
echo "File exists"
else
echo "File does not exist"
fi
We have one more operator, -d, which checks whether a directory exists.
bash
directory="/home/ubuntu"
if [ -d "$directory" ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fi
7. Loops
Loops are also available in Shell Scripting.
For Loop
bash
for i in 1 2 3 4 5
do
echo "$i"
done
Sequence Generation
We have something similar to a range in Python. Let’s focus on the sequence generation mechanism that we have here.
bash
for i in {1..10}
do
echo "Number: $i"
done
We can also define the increment value.
bash
for i in {2..20..2}
do
echo "$i"
done
Iterating Over Files
bash
for file in *.txt
do
if [ -f "$file" ]; then
echo "Text File: $file"
fi
done
Iterating Over Values
bash
for fruit in Apple Mango Banana Orange
do
echo "Fruit: $fruit"
done
While Loop
bash
i=1
while [ $i -le 5 ]
do
echo "$i"
i=$((i + 1))
done
We can also use while true to keep running a loop until we use the break statement.
bash
while true
do
read -p "Enter something (type exit to stop): " input
if [ "$input" = "exit" ]; then
break
fi
echo "You entered: $input"
done
Until Loop
This is something special that we have in Shell Scripting. It is completely opposite of the while loop.
The loop will keep on running until the given condition becomes true.
bash
i=1
until [ $i -gt 5 ]
do
echo "$i"
i=$((i + 1))
done
8. Comments
We can use the hashtag (#) to add comments.
bash
# This is a comment
9. Positional Arguments
We can use $1, $2, $3, and so on to access positional arguments.
| Argument | Meaning |
|---|---|
$1 | First argument |
$2 | Second argument |
$3 | Third argument |
$@ | All arguments |
$# | Total number of arguments |
Example
bash
echo "First Argument: $1"
echo "Second Argument: $2"
echo "Third Argument: $3"
echo "All Arguments: $@"
echo "Total Arguments: $#"
10. Exit Status
$? is used to get the exit status of the last executed command.
bash
echo "Welcome to Linux"
echo "Exit Status: $?"
11. Functions
We also have functions in Shell Scripting.
Functions are the most efficient way to design or perform modular programming. We use functions to create something once and then keep using it multiple times.
For example, we can have a function that performs a particular task, and then we can call that function whenever required.
In Shell Scripting, we have two ways of defining a function.
Method 1: Without the Function Keyword
We can directly write the name of the function. We don’t need to use brackets and everything.
bash
function_name() {
commands
}
Method 2: With the Function Keyword
bash
function function_name {
commands
}
Example: Welcome Function
bash
welcome() {
echo "Welcome to Shell Scripting"
echo "Welcome to DevOps Training"
}
welcome
Example: Function With Arguments
bash
addition() {
a=$1
b=$2
sum=$((a + b))
echo "$sum"
}
result=$(addition 10 20)
echo "Addition: $result"
12. Break and Continue Statements
We can use the break statement to terminate a loop and the continue statement to skip the current iteration and move to the next iteration.
Shell Scripting Assignments
Level 1 – Basic Assignments
- Create a script to print your name, age, and city.
- Create a calculator using arithmetic operators.
- Create a script to check whether a number is even or odd.
- Create a script to check whether a file exists.
- Create a multiplication table generator.
Level 2 – Intermediate Assignments
- Create a script to find the largest of three numbers.
- Create a script to calculate the factorial of a number.
- Create a script to check whether a number is prime.