Bash Scripting Crash Course: Beginner's Guide
Introduction
In the ever-expanding universe of technology, the command line remains an essential tool for anyone seeking to harness the full potential of their operating system. At the heart of the command line lies a powerful and versatile scripting language known as Bash. If you're new to the world of Bash scripting or find it a bit intimidating, fear not! You're about to embark on a journey that will demystify the intricacies of Bash and equip you with the skills to automate tasks, streamline processes, and unlock a new realm of possibilities.
Welcome to the "Bash Scripting Crash Course: Beginner's Guide." Whether you're a seasoned programmer looking to expand your toolkit or a complete novice taking your first steps into the world of scripting, this crash course is designed to be your trusted companion. We'll start from square one, unraveling the fundamentals, and gradually building your expertise in Bash scripting.
By the end of this guide, you'll be writing Bash scripts with confidence, automating repetitive tasks, and saving precious time in your daily tech endeavors. So, fasten your seatbelt and get ready to embark on a journey that will empower you to take command of your command line. Let's dive in! Oh!, one more thing let's try to know what bash is as this course is on bash and bash scripting. So what is bash really?, well, Bash, short for "Bourne Again Shell," is a command-line shell and scripting language used primarily on Unix-like operating systems, including Linux and macOS. It serves as an interface between the user and the operating system, allowing users to interact with the system by typing text commands. Okay, now that is out of the way, let's get started!
Setting Up Our Bash Shell
Alright, to get started writing our bash scripts we need our terminal with bash available on it and a text editor to write the bash script, you know. On Mac and Linux you can open up your terminal to start interacting with the bash shell. On Windows you can install WSL to start interacting with the bash shell. For the text editor I will be using vim throughout this course, you can use the same or any other text editor. Run the command below to install vim if not available on your PC.
sudo apt install vim
Hello World
By tradition, the first program/script to write when learning a new programming language or scripting language is printing Hello, World to standard output. Therefore, let's also start with that, let's write our first script hello.sh
, Yay!!
#!/bin/bash
echo "Hello, World"
That's it, Our Hello World script, so brief. Now let's try to understand what we just wrote. The first line contains the shebang #!/bin/bash
, what does it does?, is it tells the operating system terminal what type of interpreter to use to interpret this script, which in our case is bash which is located in the bin directory inside the file system directory, so it is important to always include this at the first line of our script. The second line contains the actual command to print Hello, World to standard output, the echo
command is a Unix command that prints out whatever it takes as an argument to standard output, hence here "Hello, World". Let's run our script and see what we have.
❯ bash hello.sh
Hello, World
Voila!, Our Hello World is now printed on the console. Notice we use bash
to run the script, well, most of the time you won't be using the bash
to run your bash script, you'll be using the shorthand method which is ./hello.sh
. However, to use this method we need to first make the script an executable by running the following command chmod u+x hello.sh
, the chmod u+x
changes the mod permission for the file so users can execute the file.
Commenting
Commenting is a programming practice of adding simple English text to your code to tell other programmers or your future self what the particular code is doing. Comments are ignored by the interpreter/computer, hence they are there to help others easily understand your code.
Types of comments in Bash Scripting
Single-line Comment
Multi-line Comment
Single-line Comment
The single-line comment starts with #
follow by the English text, Like so 👇
#!/bin/bash
# This is a single line comment
echo "Hello, World"
Multi-line Comment
The multi-line comment starts with :
followed by the English text and ends with :,
Like so 👇
#!/bin/bash
:
This is a
multi-line comment
:
echo "Hello, World"
Variables
Variables? seriously what are they? well, variables are symbolic names that stores data which is referenced and manipulated within a program. In short you can think of it as a labeled container or storage that stores data for later use.
#!/bin/bash
# Variables
NAME="Ayo"
echo "My Name is $NAME"
# variable with integer
AGE=25
echo "Age is $AGE"
# Passing commannd output to a variable
COMMAND=`uname -n`
echo "PC Hostname is $COMMAND"
Output:
My Name is Ayo
Age is 25
PC Hostname is DESKTOP-0B4FGTL
Command Line Argument
What!, what is that?, well, simple, its a parameter that you pass to a program when you run it from the command line or terminal, like so 👇
./script.sh arg1
program argument
Yeah, got it, but how do we use in the script?, well let’s see.
#!/bin/bash
echo "The name of the script $0"
echo "This takes the arg1 $1"
echo "This takes all arguments $@"
echo "This gets the number of argument passed $#"
To use the argument passed, bash uses some special variables to store the argument value, $0
stores the name of the script itself, $1
stores the argument 1, $2
for argument 2 and so on. i.e $0……$N
. Other special variable are $@, $#
.
$@
stores all the parameters the passed to the program$#
stores the number of arguments passed
The name of the script ./cli.sh
This takes the arg1 AYO
This takes all arguments AYO
This gets the number of argument passed 1
Reading input from the user
#!/bin/bash
# Read input from user
read -p "Enter your firstname and Lastname: " FIRSTNAME LASTNAME
echo "Your name is $FIRSTNAME $LASTNAME"
The read command with -p
flags allows the prompt and the input to be on the same line, the FIRSTNAME and LASTNAME variable are used to store the inputted data separated by whitespace.
Arithmetic Operations
There are couple ways of performing arithmetic operations in bash, but will just stick to one here to avoid unnecessary confusion. To perform arithmetic operation in bash we can use the double parentheses expression $(( 2 + 3 ))
, bash performs mathematical operation on the expression in the double parentheses, hence the above $(( 2 + 3 ))
will be evaluated to 5. let’s see it in code.
#!/bin/bash
a=10
b=3
# Arithemetic Operations
echo "Addition: $((a + b))" # 13
echo "Subtraction: $((a - b))" # 7
echo "Multiplication: $((a * b))" # 30
echo "Division: $((a / b))" # 3
echo "Modulo: $((a % b))" # 1
echo "Exponentiation: $((a ** b))" # 1000
Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulo: 1
Exponentiation: 1000
We can also the store the result of the mathematical expression in a variable and the reference later. You can try it out, instead of directly printing out the expression result, you can first store in a variable and the echo it to stdout.
Conditionals Statements
conditional statements in programming are constructs that allow the program to make some certain decision base on specific condition.
If, Else and Elif Statement
#!/bin/bash
# Conditional Statements
if [[ $1 -eq 5 ]]; then
echo "foo"
elif [[ $1 -eq 10 ]]; then
echo "bar"
else
echo "foobar"
fi
The above code snippet is an example of if,else and elif programming construct. The code gives the program three conditions for it to make it decision, first if the first argument passed from the command is equal to 5 the program should echo foo, or if its equal 10 the program should echo bar and if none of the condition 1 and condition 2 are true the program should echo foobar.
Case Statement
similar to if and else statement, case statement is also a control statement, that allows the program to make a decision base on the case criteria.
#!/bin/bash
# Case Statements
case "$1" in
1) echo 1;;
2|3) echo 2 or 3;;
*) echo default;;
esac
Data Structures
Arrays
Arrays are data structure in programming that is used to store multiple data. Below is an example code snippet of an array data structure in bash. The array is declared with ()
containing data to be stored and assigned to a variable.
#!/bin/bash
# Arrays
myArray=(1 2 3 4 5)
# index the array to get the element at a particular index
echo "${myArray[0]}" #Output: 1
From the above code we declare and array myArray containing 1,2..5. Then we used the index notation to access a particular element in the array, just like it is, in other popular programming languages.
Maps
A map in bash is simply called an associative array in which data are stored in key value pairs. We can declare an associative array in bash by using declare keyword with the -A option, like we have in the below code snippet. We can retrieve a value from a map using its key.
#!/bin/bash
# Maps
declare -A myDict=(
["name"]="Ayo"
["age"]=19
["height"]=5.5
)
echo "${myDict["name"]}"
From the above snippet, we declare an associative array aka(map) called myDict, with the data name, age, height with their values respectively. We then retrieved the value of name Ayo
by passing the name key in myDict square bracket notation, like we have in the code echo myDict[“name“]
.
Loops
Loops is a programming construct that allows one to execute a block of code repeatedly. In bash we have 3 various types of loops; which are for, while and until
For Loop
#!/bin/bash
# For loops
for ((i = 0; i < 10; i++)); do
echo "$i"
done
# loop through an array
myArray=(1 2 4 5)
for num in "${myArray[@]}"
do
echo "$num"
done
The above code shows the basic syntax of a for loop in bash. In the first for loop, we specify a stop condition i.e we told the program when to stop the repetition in order to avoid infinite or non-stop repetition as that will crash the program which we don't want. However, for the program to reach the stop condition, we need some kind of an event to keep happening that will get us to our stop during the iterations so we won't encounter an infinite loop. From the first for loop our stop condition was when i = 10
our repetition task should terminate, so for i
to be 10 we need to have an i
, hence i = 0,
and for i
to eventually get to 10 we have the event, increment i for each iteration, hence i++
, which is why we have for (( i=0; i<10, 1++))
. For the second for loop, I will like to use an analogy, so, let's say you have a basket of tomatoes and then you’re picking out each tomatoes in the basket until every tomato has been picked and you stop picking since there’s nothing left to pick. That’s the idea of the second loop.
While Loop
Similar to the for loop, a while starts it’s iteration at a true condition until the condition becomes false. And also don’t forget we need to include the event that will help us get to the false condition.
#!/bin/bash
n=0
while [[ $n -lt 10 ]]; do
echo $n
n=$((n+1))
done
From the above code snippet, we can see that we start our iteration from n=0, with the condition of n < 10, so basically what our while loop says is while n is less than 10 which is true at the start, do this and do that to get n to the stop point. You get the gist.
Until Loops
Until loop, really an alternative to while loop with similar syntax and idea. So won’t talk much on it. Below is the basic syntax of an until loop.
#!/bin/bash
# Until Loops
p=0
until [[ $p -eq 10 ]]; do
echo $p
p=$((p+1))
done
Functions
A function is a reusable block of codes that perform a specific task. We call a function by simply writing it's name.
The key concepts of a bash function are;
Definition: This is how the function is being defined
Parameters: These are the data the function depends on which are passed when calling the function.
#!/bin/bash
# Functions
printHello () {
echo "Hello, World"
}
printHello
sum () {
echo "$(($1 + $2))"
}
sum 2 3
The above code snippet shows how a function is defined and used in bash. The first function printHello()
, simply prints Hello, World to stdout. The second function depends on 2 parameters to perform addition operation, which is why we passed 2 and 3 parameters to sum function when calling it.
Wrap Up
We've just completed simple crash course on bash scripting which is valuable skill to have as a software engineer and a cybersecurity engineer.
Where To Go From Here
Since this is a simple crash course on bash scripting, you might want to take a deeper dive into some of the discussed concepts for more solid understanding.
Hope it was fun!
If you enjoy the tutorial, be sure to like and subscribe to my newsletter for more hacking and articles.
Thank you.
Subscribe to my newsletter
Read articles from Alaran Ayobami directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alaran Ayobami
Alaran Ayobami
A nerd in a learning loop