Mastering Shell Scripting : A Comprehensive 10-Days Zero-to-Hero Shell Scripting Challenge Series [ Day 1 ]

CJ writes
6 min readApr 5, 2024

--

Hi Amigos, welcome to the exciting blog series on Shell Scripting. Over the next 10 days, we will cover important concepts along with live day-to-day activity automation.

First of all, what is Shell ? A shell is a command-line interpreter that provides a user interface for accessing an operating system’s services. It allows users to interact with the operating system by entering commands. The shell interprets these commands and executes them.

A shell script is a script written for a shell to automate tasks or perform sequences of commands. It’s essentially a program in itself, but instead of being compiled, it’s interpreted by the shell. Shell scripting is commonly used for tasks such as system administration, file manipulation, and automation of repetitive tasks

There are several types of shells available on Linux operating systems. But why we choose Bourne Again Shell ?

| 1 | An enhanced version of the Bourne Shell.

| 2 | Provides advanced features like command-line editing, job control, and shell scripting capabilities.

| 3 | It is the default shell on most Linux distributions.

Widely used due to its availability, compatibility, and rich feature set, making it suitable for both interactive command-line usage and scripting tasks. Its powerful scripting capabilities and extensive community support make it a preferred choice for system administration, automation, and customization on Unix-like systems

Let see important concepts and Syntax before writing our first shell scripting with examples

#!/bin/bash is called a “shebang” or “hashbang” line. It is a special directive at the beginning of a script file on Unix-like operating systems that tells the system which interpreter should be used to execute the script. In this case, #!/bin/bash specifies that the Bash shell should be used to interpret and execute the commands in the script. This line is essential for running shell scripts and ensures that the script is executed by the correct interpreter.

Variables :

Let’s see how to declare and Assigning a Value to variables

#!/bin/bash

# Declaring a Variable

name="CJ_Writes"
age=28

# Accessing the value of the variable

echo "The writer name is $name and his age is $age"
Output :

The writer name is CJ_Writes and his age is 28

Once the file is created, give execute permission using chmod +x variables.sh

Then, run it using ./variables.sh or sh variables.sh

Capturing Output :

Let’s see how to execute a command or operation and store its output, then access that output value in other places

#!/bin/bash

# Execute command and capture output

# Printing current dir

current_dir=$(pwd)
echo "$current_dir"

# Addition operator

a=2
b=3

add=$((a+b))
echo "The addition of a and b is $add"

# Priting Date

date=$(date +%d-%m-%Y)
echo "The date is $date"
Output : 

/root
The addition of a and b is 5
The date is 05-04-2024

Control Statements :

Let’s see how to use if, else, elif, for, and while statements to control how your script executes based on conditions or for repeated actions

If-else statements :

This statement is used for conditional branching, allowing your script to make decisions based on certain conditions

For Loop :

The for loop in Bash is typically used when you know in advance how many times you want to iterate over a block of code or a list of items

While Loop :

The while loop, on the other hand, is used when you want to repeat a block of code as long as a certain condition is true

#!/bin/bash

a=30
b=20

#If else loop

if [[ $a -gt $b ]]; then
echo "The $a is greater then $b"
else
echo "No, it's not"
fi

#If Else If

score=100

if [[ $score -ge 90 ]]; then
echo "Grade: A"
elif [[ $score -ge 80 ]]; then
echo "Grade: B"
elif [[ $score -ge 70 ]]; then
echo "Grade: C"
elif [[ $score -ge 60 ]]; then
echo "Grade: D"
else
echo "Grade: F"
fi

#For Loop

for i in {1..5}; do # Loop from 1 to 5 (inclusive)
echo "Iteration number: $i"
done

#While Loop

count=0
while [[ $count -lt 3 ]]; do # Keep looping as long as count is less than 3
echo "Looping: $count"
count=$((count + 1)) # Increment count
done
Output : 

The 30 is greater then 20
Grade: A
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
Looping: 0
Looping: 1
Looping: 2

Functions :

It helps for reusable blocks of code for common tasks. Let’s see how to create a function and use it effectively. In this example, we are declaring a function and using the global and local scopes of variables effectively. This is just a sample of a function, upcoming blogs will explore more of it

#!/bin/bash

var1='A'
var2='B'

my_function () {
local var1='C'
var2='D'
echo "Inside function: var1: $var1, var2: $var2"
}

echo "Before executing function: var1: $var1, var2: $var2"

my_function

echo "After executing function: var1: $var1, var2: $var2"
Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: D

Array :

An array is a data structure that stores a collection of elements, where each element can be accessed using an index or a key. Array are used to organize and manipulate data in a structured manner

#!/bin/bash

array=("apple" "mango" 30)

echo "Display the Array data"

for item in "${array[@]}"; do
echo "$item"
done

echo "After adding an element to the array "
array+=("grape")

for item in "${array[@]}"; do
echo "$item"
done

echo "After Unset a value"

unset 'array[2]'

for item in "${array[@]}"; do
echo "$item"
done
Output : 

Display the Array data
apple
mango
30

After adding an element to the array
apple
mango
30
grape

After Unset a value
apple
mango
grape

String Manipulation :

Let’s see how to do string manipulation

#!/bin/bash

#Count string character

greeting="Hello, world!"
echo "Length of greeting: ${#greeting}"

#Arithmetic operation

total_files=6
echo "Total files: $((total_files - 1))"
Length of greeting: 13
Total files: 5

Error handling :

Error handling in shell scripting involves managing unexpected situations or errors that may occur during the execution of a script. Here’s an example of how you can handle errors

Error Output :

By default, error messages are sent to the standard error stream (stderr), while normal output is sent to the standard output stream (stdout). This separation allows you to distinguish error messages from regular output.

Exit Status :

Each command executed in a shell script returns an exit status, which indicates whether the command succeeded or failed.

Conventionally, a status of 0 indicates success, while any non-zero status indicates an error.

Error Trapping :

Trap command allows you to set up traps for signals or errors within your script.

By trapping errors (ERR), you can specify actions to be taken whenever an error occurs.

#!/bin/bash

handle_error() {
echo "Error: $1" >&2
exit 1
}

test() {
echo "Started running..."
ls /nonexistent_directory
}

trap 'handle_error "An error occurred in line $LINENO"' ERR

test

echo "Command executed successfully."
Started running...
ls: cannot access '/nonexistent_directory': No such file or directory
Error: An error occurred in line 15

File Handling :

Most of the time, we use shell scripting to interact with files. Shell scripting offers various operators and commands to check and perform different properties and functionalities associated with files

Let’s see a very simple example of file operation. In upcoming days, we will complete day-to-day activity scripts based on file operation tasks

We are going to create a file if it doesn’t exist, then write into the file. After that, we’ll read from the file

#!/bin/bash

read -p "Enter the name of the file that you wanna create : " filename

if [ -e $filename ]; then
echo "$filename already exists"
else
touch $filename
echo $filename created successfully
fi

echo "Test done" > $filename

while IFS= read -r line; do
echo "$line"
done < "$filename"
Enter the name of the file that you wanna create : test
test created successfully
Test done

And that’s a wrap! Thanks for tuning in. Loads of love to you all! ❤️

--

--

CJ writes

Tech explorer passionate about #DevOps, ☁️ #Cloud, 🤖 #AI. Join me as we decode tech trends and discuss global incidents! 🌐