Bash Scripting For Dummies
In this article I’ll go over the very basics of bash scripting so that by the end of it you’ll have an idea what it means and how can you use it for your own needs
UNDERSTANDING BASH
So a shell is a utility that allows us to directly interact with the kernel through issuing commands and it’s considered a very powerful tool and this shell comes in “flavors” that act as environments
Think of an environment this way, MS PowerPoint is an environment to produce and display presentation slides, for example you can’t view those slides inside another software like the calculator
In that sense, a shell is an environment to run commands directly instead of the traditional GUI way of clicking and dragging stuff and like i said that’s a huge advantage for automation and productivity
Other shells include :-
- Python : yes the programming language, it also has an interactive python shell which means it only runs Python commands
- zsh : also another shell environment in many Linux distros
- Powershell : Windows based shell environment
TO BASH OR NOT TO BASH
So a very common question might be “when do i use bash and why”, to answer this let’s consider this real life scenario, you’re an ethical hacker / pentester and you were tasked to scan a network for a specific service running ( let’s say ssh } and try to brute force into that with default credentials, how do you plan on doing that MANUALLY ?????
Here comes the power of shell scripting, with the presence of the powerful built in command line tools in linux, that task could be done very easily with a simple script that could save you a lot of time
Other uses may include :-
- automating sending business emails with
ssmtp
- fetching data from an API to send via email or save to a directory
- regularly backup files
- integrate with other powerful tools you have installed
- the list could literally go on further
PREREQUISITES
A basic Linux knowledge is required as i won’t really go over EXACTLY every command so brush up on your command line skills and be familiar with basic commands
EXCITED ENOUGH ? LET’S START BASHING
To begin scripting you first need to locate your bash location, to do that simply run which bash
and It’ll return the path to it
In your favorite text editor, in my case it’s just nano since we’re not doing much, type in this very minimal bash script and save it as hello.sh
#! /usr/bin/bashecho "hello world"
Now to run the script we firstly need to make it executable so chmod +x hello.sh
and now we can just type ./hello.sh
and should see a ‘hello world’ printed to the screen
VARIABLES IN BASH
To declare a variable, simply name it and assign a value to it like so and to reference it we use dollar sign in front of the variable name
#! /usr/bin/bash
name="mark"
echo $name
PASSING ARGUMENTS TO OUR SCRIPT
If you’ve programmed long enough and downloaded tools, you’re probably familiar with passing arguments to a script to be used, It’s an essential functionality in most command line tools so let’s learn how to pass those and echo them back for the sake of the demo only
#! /usr/bin/bash
echo $1
echo $2
echo $3
# this is a comment btw
# another syntax is
for i in "$@"
do
echo "$i"
done
# more on this stuff later
USER INPUT IN BASH
Best way to take user input it and directly assign it to a variable is the following
#! /usr/bin/bashread -p "enter your age: " age
echo "you entered $age"
LOGICAL OPERATORS
Bash has a bit tricky way to conduct logical comparisons so please stick to those notes
- use double or single square brackets [[]] as it enables you to use powerful operators
- use single or double (( )) in order to use the usual =, !=, >, <, ≤, ≥
- ALWAYSSSS leave a little space on both ends of square brackets and {}- for example
if [[ "$name" == "adam" ]]
then
echo "hi adam we missed you"
else
echo "welcome $name"
fi
Personally that advice saved me tons of time figuring out why is my script not running
4. ALWAYSSSS use double quotes when comparing variables
[[ -e "$file" ]] # True if file exists
[[ -d "$file" ]] # True if file exists and is a directory
[[ -f "$file" ]] # True if file exists and is a regular file
[[ -z "$str" ]] # True if string is of length zero
[[ -n "$str" ]] # True is string is not of length zero
# Compare Strings
[[ "$str1" == "$str2" ]]
[[ "$str1" != "$str2" ]]
# Integer Comparisions
[[ "$int1" -eq "$int2" ]] # $int1 == $int2
[[ "$int1" -ne "$int2" ]] # $int1 != $int2
[[ "$int1" -gt "$int2" ]] # $int1 > $int2
[[ "$int1" -lt "$int2" ]] # $int1 < $int2
[[ "$int1" -ge "$int2" ]] # $int1 >= $int2
[[ "$int1" -le "$int2" ]] # $int1 <= $int2
Taken from this amazing source so all credits to him ♥️
CONDITIONALS AND LOOPS
- Simple
for loop
for (i=0; i<10; i++)
do
echo "current number $i"
done
- a
for in
loop with a clever array syntax 👀
for i in {1..20}
do
echo "current iteration $i"
done
while
loop
i=10while [[ "$i" -ge 1 ]]
do
echo "current iteration: $i"
done
until
loop
i=1
until [[ "$i" -eq 10 ]]
do
echo "unitl $i"
((i++))
done
ARRAYS IN BASH
The most common data structure in programming is arrays as they allow us to store multiple values at once, unlike a variable
Let’s see how can we declare an array and how to iterate over it
names=(jake mark john bob alice)
Declare an array by using parenthesis and without a comma separating elements or even double / single quotes in case of a string
To access an array element we use the elements index like this “${colors[1]}” and since the @ sign means “all” in bash, we iterate over an array this way
for i in "${colors[@]}"
do
echo "$i"
done
AND FINALLY FUNCTIONS
A function is a block of code you wish to execute many times so instead of writing it over and over, you create a function and call it by name whenever you need it
Let’s create a quick little function that greets anyone who enters their name
CONCLUSION
Bash scripting is a powerful way to automate tasks on Linux and can be used in endless ways and boosts productivity and having basic knowledge of it is important if you’re planning on becoming an ethical hacker or system administrator or simply want to automate tedious boring tasks and we’ll hopefully explore more in later blogs and build interesting tools with it
Thanks so much for reading ♥️