TryHackMe | Bash Scripting Walkthrough

Enes Cayvarlı
14 min readDec 4, 2022

Hi there, I’m glad to see you here. In this article, we’ll learn “Bash Script” and solve the “Bash Scripting” room in TryHackMe together. In some sections, I’ll share brief about the subject. Don’t forget! You must always research to learn more. I hope it will be helpful for you. Let’s start!

Bourne-Again Shell

This is a few things among many that you will learn in this room:

-Bash syntax

-Variables

-Using parameters

-Arrays

-Conditionals

-For Loops

-Functions

Introduction

#!/bin/bash

What is bash?

Bash (Bourne-Again Shell) is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell.

What is a shell?

In computing, a shell program provides access to an operating system’s components. The shell gives users (or other programs) a way to get “inside” the system; the shell defines the boundary between inside and outside.

What is bash used for?

Bash, like other CLIs, is used for any computer application that requires precision when working with files and data, especially where large numbers of files or large quantities of data need to be searched, sorted, manipulated or processed in any way.

Our first simple bash scripts

Ok now that we have had a brief introduction to what bash is and what it is used for let’s jump right into some examples!

First of all let’s lay out our structure. A bash script always starts with the following line of code at the top of the script.

Shebang: In computing, a shebang is the character sequence consisting of the characters number sign and exclamation mark (#!) at the beginning of a script. You will always see #!/bin/bash as the first line when writing or reading bash scripts. Shebang starts with #! characters and the path to the bash or other interpreter of your choice.

Shebang

Step 1: Create bash script file using touch command.

touch command is a Linux command is mainly used to create empty files, and change timestamps of files or folders.

Note: A file with .sh extension is a scripting language commands file that contains computer program to be run by Unix shell.

Step 2: In Unix-like operating systems, the chmod command is used to change the access mode of a file. The name is an abbreviation of change mode.

r: Permission to read the file.

w: Permission to write (or delete) the file.

x: Permission to execute the file.

Step 3: Open the file you created using a text editor.

Lets get into some basic examples.

#!/bin/bash
echo "Hello World!"

This will return the string “Hello World”. The command echo is used to output text to the screen, the same way as print in python.

Note: You can run it using “./”

You can also perform normal Linux commands inside your bash script and it will be executed if formatted right. For example we can run the command ls inside our bash script and we will see the output when we run the file.

#!/bin/bash
echo "Hello World!"
whoami
id

It is basically the concatenation of the strings “who”, “am”, “i” as whoami. It displays the username of the current user when this command is invoked.

id command in Linux is used to find out user and group names and numeric ID’s (UID or group ID) of the current user or any other user in the server.

Q1: What piece of code can we insert at the start of a line to comment out our code?

A1: #

Q2: What will the following script output to the screen, echo “BishBashBosh”

A2: BishBashBosh

#!/bin/bash
echo "BishBashBosh"

Variables

A bash variable acts as temporary storage for a string or a number. Variables also make it easy for users to write complex functions and perform various operations.

Note: Please note that for variables to work you cannot leave a space between the variable name, the “=” and the value. They can not have spaces in.

Where we give the value of Enes and assign it to the variable name. So how would we now use our variable?

#!/bin/bash
name="Enes"

We have to add a $ onto front of our variable name in order to use it.

#!/bin/bash
name="Enes"
echo $name

If we test this out in our own terminal we get something like this:

Example:

#!/bin/bash
user=$(whoami)
echo "How are you today $user?"

We can also use multiple variables in something like an echo statement. You aren’t just limited to using 1!

#!/bin/bash
name="Enes"
age="24"
echo "$name is $age years old"

Some Features

1-Reassignment: You can assign different values ​​to the same variable.

#!/bin/bash
# This script used for variable practice.
# Assign a value to a variable.
WORD="script"
echo "${WORD}ing is fun!"
# Change the value stored in the WORD variable.
WORD="hack"
echo "${WORD}ing is fun!"

2-Comment Line: When writing Bash scripts, it is always a good practice to make your code clean and easily understandable. Bash ignores everything written on the line after the hash mark (#).

3-Blank Line: They’re just there to make things more readable and easier for us humans. Again the comments and blank lines don’t affect the execution of the program.

Answer the following questions and use this piece of code to guide you.

Q1: What would this code return?

A1: Jammy is 21 years old

#!/bin/bash
name="Jamy"
age="21"
echo "$name is $age years old"
city="Paris"
country="France"

Q2: How would you print out the city to the screen?

A2: echo $city

#!/bin/bash
name="Jamy"
age="21"
city="Paris"
country="France"
echo "$city"

Q3: How would you print out the country to the screen?

A3: echo $country

#!/bin/bash
name="Jamy"
age="21"
city="Paris"
country="France"
echo "$country"

Parameters

Shell Script parameters are the entities that are used to store variables in Shell.

Shell Parameters

We will firstly look at parameters specified using the command line when running the file. These come in many forms but often have the “$” prefix because a parameter is still a variable.

Let’s start by declaring a parameter that is going to be our first argument when running our bash script.

#!/bin/bash
name=$1
echo $name

We now run our script with “./test.sh Enes”

Example:

#!/bin/bash
echo "Execution of script: $0"
echo "Please enter the name of user: $1"

Example:

#!/bin/bash
name=$1
echo "Good morning $name!"
sleep 1
echo "You're looking good today $name!"

Sleep is a command-line utility which allows us to suspend the calling process for a specified time. In other words, Bash sleep command is used to insert a delay or pause the execution for a specified period of time.

Example:

#!/bin/bash
name=$1
user=$(whoami)
whereami=$(pwd)
date=$(date)
echo "Good morning $name!"
sleep 1
echo "You're looking good today $name!"
sleep 2
echo "You are currently logged in as $user."
sleep 1
echo "And you are in the directory $whereami."
sleep 1
echo "Also today is: $date"

So what if we wanted the 2nd argument? Well the process is very simple and we simply add a $2 instead of name=$1

Then run with “./test.sh Enes Kevin”

#!/bin/bash
name=$2
echo $name

Example:

#!/bin/bash
name=$1
compliment=$2
echo "Good morning $name!"
sleep 1
echo "You're looking good today $name!"
sleep 1
echo "You have the best $compliment $name!"

What if we didn’t want to supply them like this however, and instead it would let us type in our name in a more interactive way, we can do this using read.

This code will hang after its ran, this gives you the opportunity to type in your name.

#!/bin/bash
echo "Enter your name:"
read name
echo "Your name is $name"

And we can see that it worked!

Example:

#!/bin/bash
read -p "Enter your name: " name
echo "Your name is $name"

Example:

#!/bin/bash
# User Input
echo "Please enter your full name: "
read FNAME LNAME
echo "Your name is $FNAME $LNAME"

Example:

#!/bin/bash
echo "What is your name?"
read name
echo "Good morning $name!"
sleep 1
echo "You're looking good today $name!"

Q1: How can we get the number of arguments supplied to a script?

A1: $#

Q2: How can we get the filename of our current script(aka our first argument)?

A2: $0

Q3: How can we get the 4th argument supplied to the script?

A3: $4

Q4: If a script asks us for input how can we direct our input into a variable called ‘test’ using “read”

A4: read test

Q5: What will the output of “echo $1 $3” if the script was ran with “./script.sh hello hola aloha”

A5: hello aloha

#!/bin/bash
echo $1 $3

Arrays

Arrays are used to store multiple pieces of data in one variable, which can then be extracted by using an index.

-Arrays use indexing meaning that each item in an array stands for a number.

-All indexes start at position 0.

We have the variable name, in our case “transport”.

Item/Index

We then wrap each item in brackets leaving a space between each item.

We can then echo out all the elements in our array like this:

#!/bin/bash
transport=('car' 'train' 'bike' 'bus')
echo "${transport[@]}"

Where the “@” means all arguments, and the “[]” wrapped around it specifies its index.

So what if we wanted to print out the item train.

We would simply type: echo “${transport[1]}”

Because the train is at index position 1.

#!/bin/bash
transport=('car' 'train' 'bike' 'bus')
echo "${transport[1]}"

The last thing we will cover is if we want to change an element, or delete it. If we wanted to remove an element we would use the unset utility.

#!/bin/bash
transport=('car' 'train' 'bike' 'bus')
unset transport[1]
echo "${transport[@]}"

This now removes the train item, if we wanted to we could echo it back out and see that it is indeed gone. Now lets set it to something else.

#!/bin/bash
transport=('car' 'train' 'bike' 'bus')
transport[1]='subway'
echo "${transport[@]}"

Given the array please answer the following questions.

Q1: What would be the command to print audi to the screen using indexing.

A1: echo “${cars[1]}”

#!/bin/bash
cars=('honda' 'audi' 'bmw' 'tesla')
echo "${cars[1]}"

Q2: If we wanted to remove tesla from the array how would we do so?

A2: unset cars[3]

#!/bin/bash
cars=('honda' 'audi' 'bmw' 'tesla')
unset cars[3]
echo "${cars[@]}"

Q3: How could we insert a new value called toyota to replace tesla?

A3: cars[3]=’toyota’

#!/bin/bash
cars=('honda' 'audi' 'bmw' 'tesla')
cars[3]='toyota'
echo "${cars[@]}"

Conditionals

When we talk about conditionals it means that a certain piece of code relies on a condition being met, this is often determined with relational operators, such as equal to, greater than, and less than.

We will make a simple if statement to check if a variable is equal to a value, we will also make a script that checks if a file exists and that it is writeable, if it is we will write a message to that file, if not writeable it will delete it and make a new one.

Note: If statements always use a pair of brackets and we need to leave a space on both sides of the text (the bash syntax). We also always need to end the if statement with fi.

First, we will discuss the basic syntax of an if statement.

All if statements look like so:

#!/bin/bash
if [[ something comparison something else ]]
then
something
else
something different
fi

Let’s look at an example:

#!/bin/bash
count=10
if [[ $count -eq 10 ]]
then
echo "True"
else
echo "False"
fi

Example:

#!/bin/bash
echo "Hey, do you like coffee? (y/n)"
read answer
if [[ $answer == "y" ]]
then
echo "You are awesome!"
else
echo "Leave right now!"
fi

Example:

#!/bin/bash
echo "Please enter your username:"
read NAME
if [[ "$NAME" == "Elliot" ]]
then
echo "Welcome back Elliot!"
else
echo "Invalid username!"
fi

Here a variable is being declared as 10 and in the top line of the if statement the variable $count is being compared to the integer 10.

If they are equal then it outputs true, if its false it outputs false. As we know 10 is equal to 10 so it outputs true.

Operators

For more:

https://www.tutorialspoint.com/unix/unix-basic-operators.htm

So now let’s use this to make a little script that compares an input (a parameter) and checks it against a value to check if it’s true or not. A guessing game if you will.

#!/bin/bash
value="guessme"
guess=$1
if [[ "$value" == "$guess" ]]
then
echo "They are equal."
else
echo "They are not equal."
fi

Now let’s create another script where we will use 2 conditions simultaneously and coming back to a concept we learnt in the first lesson.

We want to make a script that we will perform on a file given by a parameter.

We then check if it exists and if it has write permissions. If it has write perms then we echo “hello” to it. If it is either non-accessible or doesn’t exist we will create the file and echo “hello” to it.

#!/bin/bash
filename=$1
if [[ -f "$filename" ]] && [[ -w "$filename" ]]
then
echo "hello" > $filename
else
touch "$filename"
echo "hello" > $filename
fi

The -f checked if the file existed.

The -w checked if the file was writable, without write permissions we wouldn’t be able to output our text into the file.

Example:

#!/bin/bash
if [[ -d /usr/share/wordlists ]]
then
echo "Yes it exists."
else
echo "The directory doesn't exist."
fi

-d: Checks if file is a directory; if yes, then the condition becomes true.

Example:

#!/bin/bash
if [[ -e /usr/share/wordlists/rockyou.txt ]]
then
echo "Yes it exists."
else
echo "The file doesn't exist."
fi

-e: Checks if file exists; is true even if file is a directory but exists.

Q1: What is the flag to check if we have read access to a file?

A1: -r

Q2: What is the flag to check to see if it’s a directory?

A2: -d

For Loops

Like any other programming language, bash shell scripting also supports for loops to perform repetitive tasks. It helps us to iterate a particular set of statements over a series of words in a string, or elements in an array.

Example:

#!/bin/bash
for n in {1..5}
do
echo $n
done

Example:

#!/bin/bash
s=("football" "basketball" "volleyball")
for n in ${s[@]}
do
echo $n
done

Functions

Abash function is essentially a set of commands that can be called numerous times. The purpose of a function is to help you make your bash scripts more readable and to avoid writing the same code repeatedly.

Example:

#!/bin/bash
function test_shadow {
if [[ -e /etc/shadow ]]
then
echo "Yes it exists."
else
echo "The file doesn't exist."
fi
}
function test_passwd {
if [[ -e /etc/passwd ]]
then
echo "Yes it exists."
else
echo "The file doesn't exist."
fi
}
# function call
test_shadow
test_passwd

Finally, I recommend you review the resources section, watch bash script videos on HackerSploit and NetworkChuck youtube channels, and try the examples in the article yourself.

No responses yet

Write a response