Shell Scripting: Real-World Applications
Hello! I'm Anas , a DevOps and Cloud enthusiast with a passion for building scalable, efficient, and secure infrastructure. With a strong focus on automation, containerization, and orchestration, In this blog I'll be diving into the shell scripting in detail.
Table of contents
What is shell?
What is Shell Scripting for DevOps?
Shell scripting real word application
Conclusion
What is Shell?
Shell: A program that bridges the gap between the user and the kernel.
Function: Interprets and executes commands from the user.
Popular Shells
Bourne Shell (
sh
): The original Unix shell.C Shell (
csh
): Features a syntax similar to the C programming language.Korn Shell (
ksh
): Merges features fromsh
andcsh
.Bourne Again Shell (
bash
): The most commonly used shell in Linux distributions.
What is Shell Scripting for DevOps?
A shell is a user interface that allows a user to interact with a computer system. More specifically, a shell is a command-line interface (CLI) that provides a way for users to enter commands and execute them on a computer system.
Linux shell scripting is a process of writing scripts, or programs, that are executed in a Linux shell.
A shell script is a text file that contains a series of commands that can be executed together in sequence, similar to a batch file in Windows.
Using shell scripting we can automate manual tasks to save time and increase efficiency hence it also helps in avoiding human error by doing things on its own with set of commands.
What is
#!/bin/bash?
can we write#!/bin/sh
as well?#!/bin/bash
is called the shebang or hashbang, which is a special construct that is used at the beginning of a script file in Linux/Unix systems to tell the system which interpreter to use to execute the script.It tells the system to use the Bash shell to interpret and execute the script. There are many shells sh, zsh and bash in Linux.
Similarly,
#!/bin/sh
would tell the system to use the Bourne shell (sh) to interpret and execute the script.
Bash is a more advanced shell than the Bourne shell and provides additional features such as command-line editing, command history, and job control that are not available in the basic Bourne shell.
So if your script uses Bash-specific features, it is better to use #!/b
in/bash
shebang.
Shell scripting real word application
Task 1
Create a shell script in the home directory called check_
dir.sh
. The script should print the line Directory exists
if the directory /home/bob/calest
on
exists. If not, it should print Directory not found
if [ -d "/home/bob/caleston" ] then echo "Directory exists" else echo "Directory not found" fi
Task 2
Create a shell script in the home directory called check_
greater.sh
. The script should check the greater of the two command line arguments $1
and $2
and print which ever is greater
if [ $1 -gt $2 ] then echo $1 else echo $2 fi
Task 3
Develop a shell script /home/bob/
print-month-name.sh
that accepts the number of a month as input and prints the name of the respective month. eg ./
print-month-name.sh
1
should print January
and ./
print-month-name.sh
5
should print May
. Also keep these in mind.
The script must accept a month number as a command line argument.
If a month number is not provided as command line argument, the script must exit with the message
No month number given
.
The script must not accept a value other than 1
to 12
. If not the script must exit with the error Invalid month number given
.
month_number=$1 if [ -z $month_number ] then echo "No month number given. Please enter a month number as a command line argument." echo "eg: ./print-month-number 5" exit fi if [[ $month_number -lt 1 ]] || [[ $month_number -gt 12 ]] then echo "Invalid month number given. Please enter a valid number - 1 to 12." exit fi if [ $month_number -eq 1 ] then echo "January" elif [ $month_number -eq 2 ] then echo "February" elif [ $month_number -eq 3 ] then echo "March" elif [ $month_number -eq 4 ] then echo "April" elif [ $month_number -eq 5 ] then echo "May" elif [ $month_number -eq 6 ] then echo "June" elif [ $month_number -eq 7 ] then echo "July" elif [ $month_number -eq 8 ] then echo "August" elif [ $month_number -eq 9 ] then echo "September" elif [ $month_number -eq 10 ] then echo "October" elif [ $month_number -eq 11 ] then echo "November" elif [ $month_number -eq 12 ] then echo December fi
Task 4
Develop a new script at /home/bob/
launch-rockets.sh
to call the create-and-launch-rocket
script to launch 5 rockets for the following missions using a for
loop. lunar-mission
, mars-mission
, jupiter-mission
, saturn-mission
, mercury-mission
for mission in lunar-mission mars-mission jupiter-mission saturn-mission mercury-mission do bash /home/bob/create-and-launch-rocket $mission done
Task 5
Create a simple script called loop.sh
at /home/bob
. The script should make use of a loop and print the numbers 31 to 40
with each number in a new line.
for i in {31..40}
do
echo $i
done
Task 6
We have some images under the directory /home/bob/images
. Develop a script /home/bob/
rename-images.sh
to rename all files within the images folder that has extension jpeg
to jpg
. A file with any other extension should remain the same.
for file in /home/bob/images/*; do
if [ "${file##*.}" == "jpeg" ]; then
new_file=$(echo "$file" | sed 's/jpeg/jpg/g')
mv "$file" "$new_file"
fi
done
if
statement checks if the file extension is .jpeg
using the parameter expansion ${file##*.}
, which removes the longest prefix that matches *.
(i.e., everything before the last dot). If the result is jpeg
, then the file extension is .jpeg
.
If the file extension is .jpeg
, the script uses sed
to replace jpeg
with jpg
in the file name, and stores the result in the new_file
variable.
Task 7
Let us now build a menu driven calculator program. Develop a script /home/bob/
calculator.sh
that when run:
Shows a menu-driven program with the following options:
1.Add 2.Subtract 3.Multiply 4.Divide 5.Quit
Depending on the input, the program must ask for 2 numbers -
Number1
andNumber2
and then print the result in the formAnswer=6
.The program must show the menu again until the user selects option 5 to quit.
while true do echo "Menu:" echo "1. Add" echo "2. Subtract" echo "3. Multiply" echo "4. Divide" echo "5. Quit" read -p "Enter your choice: " choice case $choice in 1) read -p "Enter Number1: " num1 read -p "Enter Number2: " num2 result=$(( num1 + num2 )) echo "Answer=$result" ;; 2) read -p "Enter Number1: " num1 read -p "Enter Number2: " num2 result=$(( num1 - num2 )) echo "Answer=$result" ;; 3) read -p "Enter Number1: " num1 read -p "Enter Number2: " num2 result=$(( num1 * num2 )) echo "Answer=$result" ;; 4) read -p "Enter Number1: " num1 read -p "Enter Number2: " num2 if [ $num2 -eq 0 ]; then echo "Error: Division by zero is not allowed." else result=$(( num1 / num2 )) echo "Answer=$result" fi ;; 5) break ;; *) echo "Invalid choice. Please choose a valid option." ;; esac done
Task 8
Automating Backups
Create a shell script to automate the backup process.
# Define source and destination directories
SOURCE="/home/user/documents"
DESTINATION="/home/user/backup"
# Create backup directory if it doesn't exist
mkdir -p $DESTINATION
# Copy files from source to destination
cp -r $SOURCE/* $DESTINATION/
# Print success message
echo "Backup completed successfully!"
Save the script as
backup.sh
.Make it executable: chmod +x backup.sh
Schedule the script to run daily using
cron
: crontab -eAdd this line to schedule the backup at midnight every day:
0 0 * * * /path/to/backup.sh
Task 9
Ensuring that disk usage on a server does not exceed a critical limit to avoid potential issues.
#Define threshold (in percentage)
THRESHOLD=80
#Get the current disk usage
DISK_USAGE-S (of grep awk '{print $5 | sed 's/k//g')
#Check if the disk usage exceeds the threshold
if [ $DISK_USAGE -gt STHRESHOLD ] ;
then
#Send an alert (e.g., email or logging)
echo "Disk usage is at ${DISK_USAGE}, which is above the threshold of ${THRESHOLD}!" mails "Disk Usage Alert" admin@example.com
fi
Conclusion
Shell scripting is a powerful tool in the hands of a DevOps engineer. By automating tasks, managing infrastructure, and optimizing workflows, you can significantly enhance your productivity. Start scripting today and elevate your DevOps capabilities! Shell scripting is an invaluable tool in the Linux ecosystem, enabling users to automate tasks and streamline processes. Whether you are a system administrator, developer, or devOps , shell scripts can significantly enhance your productivity.
I hope you find this guide on learning Shell scripting both enjoyable and valuable. If you did , please consider following and like it to show your support.
Happy Learning !!