Have you ever wondered how computers can do tasks all by themselves without anyone touching them? It's like magic, but there's a special way to tell the computer what to do, step by step. This is called scripting.
This article will explore the basics of Bash scripting, provide practical examples, and guide you through creating your scripts.
Let's dive in!
Introduction
What is Bash Scripting?
Bash scripting is a powerful tool for automating tasks on Unix-like operating systems, such as Linux and macOS.
Bash, short for the "Bourne Again Shell," is a powerful scripting language that enables users to automate repetitive tasks, streamline complex workflows, and efficiently manage system operations instead of doing them manually.
Overall, bash scripting is an essential skill for system administrators, developers, and anyone looking to optimize their computing tasks.
In Bash scripting, the Shebang #!/bin/bash
, serves as the interpreter used to execute tasks on any script. In other words, it tells the system to use the specified interpreter to run the script.
Prerequisite
- Vagrant virtual machine
- Good understanding of Linux commands
Basics to Know Before Writing a Bash Script
Before diving into writing Bash scripts, it's essential to understand some fundamental concepts and components of Bash scripting. Here are the basics you need to know:
Familiarize yourself with basic Unix commands like
mkdir
,touch
, andecho
.Understand file permissions and how to change them using
chmod
. For example, to make your script executable, usechmod +x
. The X stands for executionUse a text editor like Nano or Vim to write and edit scripts.
For Nano -nano myscript.sh
For Vim -vi myscript.sh
Add comments in your scripts using
#
symbol. They help explain what the script does and are ignored during execution.
# This is a comment
Always start your script with a Shebang. It specifies the interpreter to be used.
Lastly, for every script, you must make sure to follow the syntax which includes the spacing, indentation, and punctuation.
Let's begin
Practical Examples of Bash Scripting
Let's start by creating a new directory that will house all our scripts. Once the directory is created, cd
into the folder and create a file with the .sh
extension. The .sh
tells you that the file is a script.
mkdir bashscript
cd bashscript
touch myscript.sh
Let's make our newly created scripts executable. This will enable us to run our script
chmod +x myscript.sh
The ll
command shows the permissions for the myscript.sh file
Next, let's play around with automation.
To do this, let's write a script that updates and upgrades our system.
This command vi myscript.sh
opens the file named script.sh
in the vi
text editor.
When the file is opened in the Vim text editor, write the following codes below:
#!/bin/bash
sudo apt update -y
sudo apt upgrade -y
Close your text editor and run this command - ./myscript.sh
Now that we have seen what automation looks like using a bash script, let's get more practical.
Statements in Bash Scripting
i. Printing statements using the echo
command.
The echo command in Bash scripting is used to print output to the terminal. Let's try it out.
First, create a script. I called my script
myscript.sh
. Then use the Vim text editor to open itvi myscript.sh
Remember to start your script with the Shebang#!/bin/bash
interpreter followed by theecho
command and your text in quotes. Then close the editor.
#!/bin/bash
echo "Florence is a Cloud Engineer who loves bash Scripting"
Run your script using the ./<name of your script>
The output will look like the image below
ii. Declaring variables.
Variables in bash scripting are used to store data and can be referenced in your script to perform operations. Here is how to declare a variable:
#!/bin/bash
name="Florence"
job="Cloud Engineer"
There should be no spaces around the equals sign. The value can be a number, a string, or the result of a command.
To read or use the value stored in a variable, you prepend the variable name with a dollar sign$
. For example:
#!/bin/bash
echo "My name is $name and I'm a $job"
When this script is run using the ./myscript.sh
this is what it will look like
iii. If Statements
The If statement allows your script to make decisions and perform different actions depending on whether a condition is true or false. In the example below, we are going to run a script that checks whether a given number is an even or odd number.
read -p "Enter a number: " number
if (( $number % 2 == 0 )); then
echo "$number is an even number"
else
echo "$number is an even number"
fi
A breakdown of the script:
read -p "Enter a number: " number
: Prompts the user to enter a number and stores it in the number variable.
if (( number % 2 == 0 )); then
: Checks if the number is even.
echo "The number $number is even."
: Prints that the number is even if the condition is true.
else
: Executes the following code if the number is not even.
echo "The number $number is odd."
: Prints that the number is odd.
fi
: Ends the if statement.
When the above script is run, here is what the result will look like
iv. While Loop
In Bash scripting, the while
loop allows you to repeatedly execute a block of code as long as a specified condition remains true. Once the condition becomes false, the loop stops executing. This is similar to a washing machine cycle: it keeps running until the timer reaches zero.
Let's write a script that checks if a particular directory exists or not. In this case, we are checking if the ~bash/loopdir
exists in our system
#!/bin/bash
while [ -d ~bash/loopdir ]; do
echo "Directory exists"
done
echo"Directory does not exist"
A breakdown of the script:
while [ -d ~/bash/loopdir ]; do
: Starts a while loop that checks if the directory ~/bash/loopdir exists.
echo "Directory exists"
: If the directory exists, prints "Directory exists".
done
: Ends the while loop when the directory no longer exists.
echo "Directory not found"
: After exiting the loop, prints "Directory not found" when the directory is no longer present.
Now, that you have gotten to this point, let's do something interesting. Let's create a script that monitors the uptime of a server and logs it periodically. In this script, we are also going to incorporate a cronjob that will record the server's uptime at specified intervals.
Before we start, let me explain what a cronjob does and why it is needed.
A cron job is just like that magical clock for your computer! It helps your computer remember to do certain tasks automatically, without you having to tell it every time.
Let me be more technical now.
A cron job is a time-based job scheduler in Unix-like operating systems, including Linux. It allows users to schedule commands or scripts to run periodically at fixed times, dates, or intervals. These scheduled tasks are referred to as cron jobs, and they can automate repetitive tasks, such as backups, system maintenance, uptime monitoring, log rotation, etc.
Now, let's create that script!
With this command sudo vi log_uptime.sh
I will create a script for this particular task and make it executable using sudo chmod +x log_uptime.sh
Let's write the script.
#!/bin/bash
# Define the log file
LOG_FILE="$HOME/uptime_log.txt"
# Create the log file if it doesn't exist
if [ ! -f "$LOG_FILE" ]; then
touch "$LOG_FILE"
echo "Log file created at $LOG_FILE"
fi
# Get the current date and uptime
CURRENT_DATE=$(date '+%Y-%m-%d %H:%M:%S')
UPTIME=$(uptime -p)
# Append the uptime to the log file
echo "$CURRENT_DATE - Uptime: $UPTIME" >> "$LOG_FILE"
echo "Uptime logged at $CURRENT_DATE"
# Define the cron job command
CRON_JOB="0 * * * * $HOME/log_uptime.sh"
# List existing cron jobs
echo "Current Cron Jobs:"
crontab -l
# Add the cron job
echo "Adding new cron job:"
echo "$CRON_JOB" | crontab -
# Confirmation of added cron job
echo "New cron job added:"
crontab -l
When this script is run using the ./log_uptime.sh
command, here is what the output will be
Conclusion
Scripting in Bash is like giving instructions to your computer to do tasks automatically. This article introduced the basics of Bash scripting, providing practical examples by creating readable scripts. With Bash scripting, you can automate repetitive tasks and manage system operations efficiently.
Your feedback is very important to me. Were the explanations clear? Did the examples make sense? Let me know if there's anything specific you'd like me to cover in more detail. I'm here to ensure I meet your needs.
Thank you for reading!
Top comments (1)
This looks really good and explanatory. Welldone!