➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
Bash Scripting | Bash scripting is a powerful way to automate tasks, streamline workflows, and manage system configurations in Unix-like operating systems. With a simple text file containing a series of commands, you can perform complex tasks quickly and efficiently.
VM Setup
We will be creating four virtual machines using Vagrant to practice our Bash scripts. Create a directory, and create a Vagrantfile in it.
cd /C/workspace/
mkdir scripts/
cd scripts/
vi Vagrantfile
Put the below content in Vagrantfile. This Vagrantfile
sets up four virtual machines for Bash scripting practice. It includes scriptbox
, web01
, web02
, and web03
with specific configurations. scriptbox
has 1024 MB of RAM and a private IP of 192.168.10.12
. All VMs are assigned private network IPs and unique hostnames. These VMs provide an isolated environment for developing and testing Bash scripts effectively:-
Vagrant.configure("2") do |config|
# Define VM scriptbox
config.vm.define "scriptbox" do |scriptbox|
scriptbox.vm.box = "eurolinux-vagrant/centos-stream-9"
scriptbox.vm.network "private_network", ip: "192.168.10.12"
scriptbox.vm.hostname = "scriptbox"
scriptbox.vm.provider "virtualbox" do |vb|
vb.memory = "1024"
end
end
# Define VM web01
config.vm.define "web01" do |web01|
web01.vm.box = "eurolinux-vagrant/centos-stream-9"
web01.vm.network "private_network", ip: "192.168.10.13"
web01.vm.hostname = "web01"
end
# Define VM web02
config.vm.define "web02" do |web02|
web02.vm.box = "eurolinux-vagrant/centos-stream-9"
web02.vm.network "private_network", ip: "192.168.10.14"
web02.vm.hostname = "web02"
end
# Define VM web03
config.vm.define "web03" do |web03|
web03.vm.box = "ubuntu/jammy64"
web03.vm.network "private_network", ip: "192.168.10.15"
web03.vm.hostname = "web03"
end
end
Start the scriptbox
VM:-
vagrant up scriptbox
vagrant ssh scriptbox
sudo -i
Intro to Bash Scripting
A bash script is essentially a text file containing a series of commands. You can create a script using any text editor, such as nano, vi, or gedit. The first line of the script should specify the interpreter that will execute the script, typically Bash:-
#!/bin/bash
Making the Script Executable: After creating the script, you need to make it executable using the chmod
command:-
chmod +x script_name.sh
Running the Script: To run the script, you simply execute it from the command line:
./script_name.sh
Basic Script Structure:- Here’s a simple example of a bash script:
#!/bin/bash
# This is a comment
echo "Hello, World!" # This prints "Hello, World!" to the terminal
# Variables
NAME="John"
echo "Hello, $NAME!"
# Conditional Statements
if [ "$NAME" = "John" ]; then
echo "Your name is John"
else
echo "Your name is not John"
fi
# Loops
for i in {1..5}; do
echo "Iteration $i"
done
# Functions
greet() {
echo "Hello, $1!"
}
greet "Alice"
Yes, the .sh
extension is optional for Bash scripts. While it is common practice to use the .sh
extension to indicate that a file is a shell script, you can name your script file with any extension or even without an extension. The important part is to ensure the script is executable and has the correct shebang (#!/bin/bash
) at the beginning.
For example:
myscript.sh
myscript
myscript.bash
As long as the script is executable, you can run it with:
./myscript
Let’s get started. Create a directory to put scripts.
mkdir /opt/scripts
cd /opt/scripts/
yum install vim -y
vi firstscript.sh
In the file:-
#!/bin/bash
# first line should be shebang (#!/bin/bash)
# This script prints system info
echo "Welcome to bash script."
echo
echo "The uptime of the system is: "
uptime
echo "Memory Utilization"
free -m
echo "Disk Utilization"
df -h
the first line of the file should ideally be the shebang (#!/bin/bash) when writing a Bash script. The shebang tells the system which interpreter to use to execute the script. Without it, the script may not run as expected, especially if the default shell is not Bash.
If we try to run the script then we will get the permission denied error.
# ./firstscript.sh
-bash: ./firstscript.sh: Permission denied
Because it does not execute permission for the user.
# chmod +x firstscript.sh
# ./firstscript.sh
In vi, to see the line number we can use :se nu
Bash Variables
Variables in Bash are temporary storage in memory, holding data that a process can use while it’s running. Once the process ends, all associated data is lost. Variables in a script allow us to store and retrieve data dynamically.
Creating and Using Variables
To create a variable in Bash, simply assign a value to a variable name:
$ SKILL="DevOps"
To retrieve the value, use the dollar sign followed by the variable name:
echo $SKILL
In Bash, the dollar sign is crucial to differentiate a variable from plain text.
Example of Variables in Action: Consider the following example where we store package names in a variable and use it to install packages:
PACKAGE="httpd wget unzip"
yum install $PACKAGE -y
This will install the packages httpd
, wget
, and unzip
.
Implementing Variables in a Web Setup Script: We can enhance the web setup script by declaring variables for values that might change or be reused multiple times:
#!/bin/bash
PACKAGE="httpd wget unzip"
SVC="httpd"
URL="http://example.com/artifact.zip"
ARTIFACT="artifact"
TMP_DIR="/tmp"
# Use the variables in the script
yum install $PACKAGE -y
systemctl start $SVC
cd $TMP_DIR
wget $URL
unzip $ARTIFACT.zip
systemctl restart $SVC
This approach makes the script more flexible and maintainable. Points to consider:-
- Variable Assignment: In Bash, there should be no spaces around the
=
sign when assigning values to variables. - Quotes: Use double quotes around variables, especially when dealing with paths.
To remove the data:-
#!/bin/bash
sudo systemctl stop httpd
sudm rm -rf /var/www/html/ *
sudo yum remove httpd wget unzip -y
By using variables in Bash scripts, you can make your scripts more adaptable and easier to manage. Variables help isolate changes to specific values, reducing the need for multiple edits when updates are necessary.
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!