Skip to content
ImagineWorld

Variables, Conditionals, Loops, and Arrays

node_idnode-book_bash-shell-scripting-for-pentesters_chapter-03-variables-conditionals-loops-and-arrays
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleVariables, Conditionals, Loops, and Arrays
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Variables, Conditionals, Loops, and Arrays

Section titled “Chapter 3 — Variables, Conditionals, Loops, and Arrays”

In previous chapters, we provided information that led up to the topics we’ll be covering here. We did this by walking you through the process of getting your system set up and common commands that are used for navigating the Linux filesystem using Bash commands.

In this chapter, we’ll dive into the essentials of programming that make your code smart and efficient: variables, conditionals, loops, and arrays. Think of variables as name tags referring to data, conditionals as crossroads that decide which path your program takes, and loops as the way you can keep doing something until a certain condition is met. These concepts are the building blocks for creating dynamic and responsive programs. Whether you’re just starting or brushing up on the basics, understanding these elements is critical for any coding journey.

In this chapter, we’re going to cover the following main topics:

  • Introducing variables
  • Branching with conditional statements
  • Repeating with loops
  • Using arrays for data containers

In this chapter, you’ll need a Linux Bash Terminal to follow along. You can find this chapter’s code at https://github.com/PacktPublishing/Bash-Shell-Scripting-for-Pentesters/tree/main/Chapter03.

Think of variables as name tags or containers that store data. You can assign any data, such as text, numbers, filenames, and more, to a short and memorable variable name. Throughout your script, you can repeatedly refer to the data by its given variable name and make decisions on the data or even change the data the variable refers to. Technically, a variable is a declaration that allocates memory storage space and assigns it a value.

In the following subsections, we’ll be breaking the subject of variables into bite-sized chunks to make it easier to digest.

To declare a variable in Bash, you simply assign a value to a variable name. The syntax for declaring a variable is as follows:

variable_name=value

For example, to declare a variable named my_variable with a value of Hello, World!, you would use the following command:

my_variable="Hello, World!"

Important note

There should be no spaces around the equals sign, =. Also, it’s good practice to enclose string values in double quotes, ", as it allows for proper handling of spaces and special characters. Use single quotes to prevent expansion; double quotes if you want variables or special characters to be expanded. If you must use special characters such as $ in a double-quoted string, you can make them display as a literal character instead of being evaluated by escaping the character with a backslash – for example, \$.

One powerful feature of Bash variables is their ability to store the output of commands using command substitution. This can be achieved by enclosing the command within backticks `, or using the $() syntax. Here’s an example:

current_date=\`date\`

Alternatively, you can use the following implementation:

current_date=$(date)

Both commands will store the current date and time in the current_date variable.

In Bash, you can pass arguments to a script when you run it from the command line. These arguments are stored in special variables, which you can then use inside your script. Here’s how it works:

~ $ ./myscript.sh arg1 arg2 arg3

Inside the script, you can access these arguments using the following special variables:

  • $0: The name of the script itself
  • $n: The nth argument passed to the script, $1 through $9. Examples include $1, $2, and $3
  • ${10}: The tenth argument passed to the script (curly braces are required for arguments >= 10)
  • $#: The number of parameters
  • $?: The exit status of the last executed command
  • $$: The process ID of the current shell
  • $@: Contains the command-line arguments in an array
  • $*: Represents all the positional parameters (arguments) passed to the script or a function as a single string

To access the value of a variable, you simply use the variable’s name preceded by a dollar sign, $:

#!/usr/bin/env bash
my_string="Welcome to Bash Scripting for Pentesters!"
echo $my_string

This example code can be found in the ch03_variables_01.sh file in this chapter’s folder.

This will output the following:

Welcome to Bash Scripting for Pentesters!

The following script shows how to access command-line arguments:

#!/usr/bin/env bash
name=$1
age=$2
echo "Hello $name, you're $age years old!"

This example code can be found in the ch03_variables_02.sh file in this chapter’s folder.

If we run this script, we’ll get the following output:

~ $ bash ch03_variables_02.sh Steve 25
Hello Steve, you're 25 years old!

What would happen if you entered your first and last name without enclosing them in double quotes? Give it a try.

You can perform arithmetic operations on variables using the $(()) syntax or the let command:

#!/usr/bin/env bash
a=5
b=3
c=$((a + b))
let d=a+b
let e=a*b
echo "a = $a"
echo "b = $b"
echo "c = $c"
echo "d = $d"
echo "3 = $e"

This example code can be found in the ch03_variables_03.sh file in this chapter’s folder.

In the preceding code block, we assign a value of 5 to the a variable and 3 to the b variable. Next, we added a and b and assigned the sum to the c variable. The last two lines show addition and multiplication using the let command.

Here’s the output when we run the code:

~ $ bash ch03_variables_03.sh
a = 5
b = 3
c = 8
d = 8
3 = 15

Now that you understand how to create and access variables, we’ll move on to a special type of variable, the environment variable.

Environment variables are essentially named objects that store data used by operating system processes. These variables can influence the behavior of software on the system by providing context about the user’s environment, such as the current user’s home directory or the path to executable files.

By default, variables defined in a Bash script are local to that script. To make a variable available to other processes (such as subshells or child processes), you need to export it using the export command:

my_var="Hello, World!"
export my_var

After exporting a variable, you can access its value in subshells or child processes.

The beauty of environment variables lies in their ability to streamline processes. Without them, every time you want to run a program or script, you might need to type out the full path to its location. With environment variables, Bash knows where to look for certain files or directories because these paths are stored in variables such as PATH.

Moreover, environment variables ensure that software behaves correctly in different user environments. For instance, the HOME variable tells applications where a user’s home directory is located, allowing programs to save files in the right place without needing explicit instructions every time.

Let’s put this into perspective with some practical examples. Say you frequently access a directory that’s buried deep within your filesystem. Typing out the full path every time can be tedious. By creating a custom environment variable for this path, you can simplify the process significantly:

export MY_DEEP_DIRECTORY="/this/is/a/very/long/path/that/I/use/often"

Now, whenever you need to access this directory, you can simply type cd $MY_DEEP_DIRECTORY, and Bash will take you there instantly.

Another common use case is modifying the PATH variable. The PATH variable tells Bash where to look for executable files. If you’ve installed a program that’s not in your system’s default executable paths, you can add its location to your PATH:

export PATH=$PATH:/path/to/my/program

This addition allows you to run your program from anywhere in the Terminal without the need to specify its full path.

Notice that the path to your program is preceded by $PATH:. What this does is append the new path to the existing path. Without this, you would be overwriting your PATH and you would have errors until you fix it or reboot your computer.

Important note

If you want an environment variable to persist across reboots, put it in your .bashrc file. To make the change to .bashrc take effect, run the source ~/.``bashrc command.

Now that you have a firm grip on variables, it’s time to cement this knowledge with some practice by reviewing everything you’ve learned about them.

Let’s examine a script that includes everything we’ve covered so far in this chapter. Take a look at the following script:

#!/usr/bin/env bash
# What is the name of this script?
echo "The name of this script is $0."
# Assign command line arguments to variables
name=$1
age=$2
# Use the first two parameters.
echo "The first argument was $1, the second argument was $2."
# How many parameters did the user enter?
echo "The number of parameters entered was $#."
# What is the current process ID?
echo "The current process id of this shell is $$."
# Print the array of command line arguments.
echo "The array of command line arguments: $@"

This example code can be found in the ch03_variables_04.sh file in this chapter’s folder.

First, it’s important to point out that I’m introducing something new here. Comments in scripts start with # and continue through the end of the line. Anything that follows # on the same line isn’t printed, provided the symbol isn’t escaped. You may have noticed that on one line, we used $# to print the number of parameters provided to the script. The comment behavior doesn’t apply in this case since it’s inside double quotes, preceded by a $ symbol, and is not escaped.

You must document your scripts with comments. If you need to edit your script after some time, comments are helpful to remind you what you were trying to do and are also helpful to others if you share or publish your script.

Now, let’s run the script. There are two ways we can run it. We can run it by entering bash followed by the script’s name, or we can make the script executable and prefix the path, as shown in the following examples:

~ $ bash ch03_variables_04.sh "first arg" 2nd 3rd fourth
The name of this script is ch03_variables_1.sh.
The first argument was first arg, the second argument was 2nd.
The number of parameters entered was 4.
The current process id of this shell is 57275.
The array of command line arguments: first arg 2nd 3rd fourth
The first argument is: first arg
The second argument is: 2nd
The first and second arguments are: first arg 2nd

Next, let’s list the file permissions, as you learned to do in Chapter 2:

~ $ ls -l ch03_variables_04.sh
-rw-r--r-- 1 author author 714 Mar 20 09:28 ch03_variables_04.sh

In the preceding command, you can see that we used the -l option with the ls command to see the permissions. It’s readable and writable for the owner, and only readable by the group and others. Next, let’s use the chmod command to make it executable:

~ $ chmod +x ch03_variables_04.sh
~ $ ls -l ch03_variables_1.sh
-rwxr-xr-x 1 author author 714 Mar 20 09:28 ch03_variables_04.sh

Here, you can see that after entering the chmod command with the +x argument, the file is now executable by the owner, group, and others. And of course, you could make it executable only by the owner by using the chmod 744 ch03_variables_04.sh command instead. Please refer to Chapter 2 or run the man chmod command if you need a refresher.

Now that the file is executable, you can run it by prepending the path before the filename. You can specify the absolute or relative path, as discussed in Chapter 2. Here’s how you can run it using a relative path:

~ $ ./ch03_variables_04.sh 1 2 3 4

Important note

The shebang (#!) is the first line in a script that specifies the interpreter (program) to be used for executing the script. Using the #!/usr/bin/env bash shebang tells the shell to run the script using the Bash interpreter.

Without the shebang, the following execution method may not work because the shell may not know what program to use to execute the code.

If you don’t include a shebang and make your script executable, you have to prefix your script name with bash to be able to run your script.

By now, you should have a good grasp of how variables work. In the next section, you’ll learn how to use conditionals to make decisions and branches in your scripts.

At its core, a conditional statement in Bash is a way to tell your script, “Hey, if this specific thing is true, then go ahead and do this; otherwise, do that.” It’s the foundation of making decisions in your scripts. The most common conditional statements you’ll encounter in Bash are if, else, and elif.

The if statement is the simplest form of conditional statement. It checks for a condition, and if that condition is true, it executes a block of code. Here’s a straightforward example:

#!/usr/bin/env bash
USER="$1"
if [ $USER == 'steve' ]; then
echo "Welcome back, Steve!"
fi

This example code can be found in the ch03_conditionals_01.sh file in this chapter’s folder.

In this example, the script checks whether the current user is steve based on matching the first command-line argument. If it is, it greets Steve. Notice the syntax here: square brackets around the condition, double equals for comparison, and then indicate the start of what to do if the condition is true. The fi part at the end of the if block signifies to the shell that it’s closing out the if statement.

It’s important to point out that the semicolon (;) character has a special meaning as a command separator. Without it, this if statement block would break. Semicolons can also be used to put multiple commands on the same line. The preceding if statement can be rewritten using more semicolons, as shown here:

if [ "$USER" == 'steve' ]; then echo "Welcome back, Steve!"; fi

But what if you want to do something else when the condition isn’t met? That’s where else comes in handy. It allows you to specify an alternative action if the condition is false. Here’s an example:

#!/usr/bin/env bash
USER="$1"
if [ $USER == 'steve' ]; then
echo "Welcome back, Steve!"
else
echo "Access denied."
fi

This example code can be found in the ch03_conditionals_02.sh file in this chapter’s folder.

Now, if the user isn’t steve, the script responds with Access denied.:

~ $ bash ch03_conditionals_02.sh Somebody
Access denied.

Sometimes, you have more than two possibilities to consider. That’s where elif (short for else if) becomes useful. It lets you check multiple conditions one by one:

#!/usr/bin/env bash
if [ $USER == 'steve' ]; then
echo "Welcome back, Steve!"
elif [ $USER == 'admin' ]; then
echo "Hello, admin."
else
echo "Access denied."
fi

This example code can be found in the ch03_conditionals_03.sh file in this chapter’s folder.

In the preceding script, the USER variable comes from the environment variable for the logged-in user. Change your code in the if or elif statements so that it matches your username as needed.

When you run it while logged in as Steve, you get the following output:

$ bash ch03_conditionals_03.sh
Welcome back, Steve!

With elif, you can add as many additional conditions as you need, making your script capable of handling a wide range of scenarios.

Now that you know how to use commonly used conditional statements, let’s dive into slightly more advanced examples that are commonly used in Bash scripting.

Bash conditional statements aren’t limited to just checking whether one thing equals another. You can check for a variety of conditions, including the following:

  • Whether a file exists
  • Whether a variable is greater than a certain value
  • Whether a file is writable

In Bash, primaries refer to the expressions that are used in conditional tests within [ (single-bracket), [[ (double-bracket), and test commands. These primaries are used to evaluate different types of conditions, such as file attributes, string comparisons, and arithmetic operations. Primaries are essential building blocks in conditional statements, allowing you to test files, strings, numbers, and logical conditions. They are typically used within if, while, or until constructs to determine the flow of the script based on these evaluations.

File test primaries are used to check properties of files, such as whether they exist, are readable, are directories, and so on. The following list specifies file test primaries:

  • -e FILE: True if the file exists
  • -f FILE: True if the file exists and is a regular file
  • -d FILE: True if the file exists and is a directory
  • -r FILE: True if the file exists and is readable
  • -w FILE: True if the file exists and is writable
  • -x FILE: True if the file exists and is executable
  • -s FILE: True if the file exists and is not empty
  • -L FILE: True if the file exists and is a symbolic link

For instance, checking whether a file exists before trying to read from it can save your script from crashing:

#!/usr/bin/env bash
if [ -f "/path/to/file.txt" ]; then
echo "File exists. Proceeding with read operation."
else
echo "File does not exist. Aborting."
fi

This example code can be found in the ch03_conditionals_04.sh file in this chapter’s folder.

The -f flag tests whether the provided filename exists and is a regular file. To test for directories instead, we can use the -d flag. To test for both files and directories, we can use the -e flag. If we hadn’t checked that the file exists first, our script would have crashed. Using an if statement allows us to handle the error gracefully.

To compare integer variables in Bash, you should use the -eq, -ne, -lt, -le, -gt, and - ge primaries:

  • -eq: True if the numbers are equal
  • -ne: True if the numbers are not equal
  • -gt: True if the first number is greater than the second
  • -ge: True if the first number is greater than or equal to the second
  • -lt: True if the first number is less than the second
  • -le: True if the first number is less than or equal to the second

Here are some examples demonstrating integer comparisons:

#!/usr/bin/env bash
num1=10
num2=20
# Compare if num1 is equal to num2
if [ $num1 -eq $num2 ]; then
echo "num1 is equal to num2"
else
echo "num1 is not equal to num2"
fi

This example code can be found in the ch03_conditionals_05.sh file in this chapter’s folder.

Running this code should output the following:

num1 is not equal to num2

In the preceding code, I declared two variables. Then, I used the -eq comparison operator inside an if - else block to print the result. You can also do this all on one line, as follows:

num1=10; num2=20; [ $num1 -eq $num2 ] && echo "num1 is greater" || echo "num2 is greater"

In the preceding example, I declare two variables. Then, I put the comparison inside square brackets. The logical and (&&) operator means if the previous command is successful (that is, returns true or 0), then execute the next command. Otherwise, the logical or (||) operator means if the previous command is not successful (that is, returns a non-zero exit code), then execute the next command. Try running this code in your Terminal and check the output. You should see the following output:

num2 is greater

The following code demonstrates how to use the less than -lt operator to compare integers:

#!/usr/bin/env bash
num1=10
num2=20
if [ $num1 -lt $num2 ]; then
echo "num1 is less than num2"
else
echo "num1 is not less than num2"
fi

This example code can be found in the ch03_conditionals_06.sh file in this chapter’s folder.

Running the preceding code should output the following:

num1 is less than num2

The following code demonstrates how to use the greater-than or equal-to operator, -ge:

#!/usr/bin/env bash
num1=10
num2=20
if [ $num1 -ge $num2 ]; then
echo "num1 is greater than or equal to num2"
else
echo "num1 is not greater than or equal to num2"
fi

This example code can be found in the ch03_conditionals_07.sh file in this chapter’s folder.

This code should output the following:

num1 is not greater than or equal to num2

String comparisons in Bash are done using = and != for equality and inequality, and < and > for lexicographical comparisons. The following are string primaries in Bash:

  • -z STRING: True if the string is empty
  • -n STRING: True if the string is not empty
  • STRING1 == STRING2: True if the strings are equal
  • STRING1 != STRING2: True if the strings are not equal

Here’s an example demonstrating string comparisons:

#!/usr/bin/env bash
# Declare string variables
str1="Hello"
str2="World"
str3="Hello"
# Compare if str1 is equal to str2
if [ "$str1" == "$str2" ]; then
echo "str1 is equal to str2"
else
echo "str1 is not equal to str2"
fi
# Compare if str1 is not equal to str3
if [ "$str1" != "$str3" ]; then
echo "str1 is not equal to str3"
else
echo "str1 is equal to str3"
fi
# Lexicographical comparison if str1 is less than str2
if [[ "$str1" < "$str2" ]]; then
echo "str1 is less than str2"
else
echo "str1 is not less than str2"
fi

This example code can be found in the ch03_conditionals_08.sh file in this chapter’s folder.

Here’s the output of the script:

str1 is not equal to str2
str1 is equal to str3
str1 is less than str2

This example shows how to compare bytes in a string. To extract the first character of a string, use byte="${string:1:1}". Then, compare byte as you would any other string.

So far, we’ve been comparing simple text and integer numbers. Comparing UTF-8 encoded strings is the same as comparing English characters. Bash itself doesn’t have built-in support for direct comparison of UTF-16 encoded strings in a way that it’s aware of the encoding specifics. However, you can use external tools such as iconv to convert and compare these strings. However, that subject is beyond the scope of this book. I simply want you to be aware of this limitation and where to look should you ever need to compare UTF-16 encoded strings.

Having covered comparing conditionals in depth, next, we’ll take a look at combining conditions using logical operators.

What if you need to check multiple conditions at once? Bash has you covered with logical operators such as && (AND) and || (OR). These operators allow you to combine conditions, making your scripts even smarter. The following example shows how to use logical operators to check multiple conditions:

#!/usr/bin/env bash
if [ $USER == 'steve' ] && [ -f "/path/to/file.txt" ]; then
echo "Hello, Steve. File exists."
elif [ $USER == 'admin' ] || [ -f "/path/to/admin_file.txt" ]; then
echo "Admin access granted or admin file exists."
else
echo "Access denied or file missing."
fi

This example code can be found in the ch03_conditionals_09.sh file in this chapter’s folder.

Here, we use an if condition, which evaluates to TRUE (returns 0) if both conditions are true. This part of the code uses a logical AND, &&. This means that only if the first condition and the second condition are both true, then the result is true.

In the elif condition, if either evaluation is true, the block returns TRUE. Think of && as “If test1 AND test2 are true, return TRUE ” and || as “If test1 OR test2 is true, return TRUE, otherwise return FALSE (returns 1).”

Logical operators simplify comparisons and save us a lot of typing! Without them, we would have to write much longer and more complex code. Logical comparisons in Bash are like decision-making tools that help your script understand and react to different situations. Just as you might decide what to wear based on the weather, your Bash script uses logical comparisons to decide what actions to take based on the data it processes.

Let’s look at the case statement. It’s somewhat like the switch statement you might know from other programming languages. The case statement allows you to match a variable against a series of patterns and execute commands based on the match. It’s incredibly useful when you have multiple conditions to check against the same variable. Here’s a simple example:

#!/bin/bash
read -p "Enter your favorite fruit: " fruit
case $fruit in
apple) echo "Apple pie is classic!" ;;
banana) echo "Bananas are full of potassium." ;;
orange) echo "Orange you glad I didn't say banana?" ;;
*) echo "Hmm, I don't know much about that fruit." ;;
esac

This example code can be found in the ch03_conditionals_10.sh file in this chapter’s folder.

In this script, we use read -p to prompt the user for their favorite fruit, assign the input to the fruit variable, and use a case statement to respond with a custom message based on this variable. The *) pattern acts as a catch-all, similar to else in an if statement.

When we run it, we get the following output:

~ $ bash ch03_conditionals_10.sh
Enter your favorite fruit: pear
Hmm, I don't know much about that fruit.

Having introduced the Bash read built-in, let’s review its parameters and their effects:

  • -p prompt: Display a prompt before reading input
  • t timeout: Set a timeout for input
  • -s: Silent mode; do not echo input
  • -r: Raw input; do not allow backslashes to escape characters
  • -a array: Read input into an array
  • -n nchars: Read only nchars characters
  • -d delimiter: Read until the first occurrence of the delimiter instead of a newline

Bash conditional statements are a powerful tool in your scripting arsenal. They allow your scripts to make decisions and react to different situations intelligently. By understanding and using if, else, elif, and case, and combining conditions with logical operators such as && and ||, you can write more efficient and responsive Bash scripts.

With conditionals added to our arsenal, we’ll explore loops in the next section. Loops, when combined with conditionals and variables, make our scripting so much more powerful!

Bash loops are iteration statements, a repetition of a process. Imagine that you have the output of many lines of data from log files or vulnerability scans. Reviewing each line manually would be akin to climbing a mountain with your hands tied; possible, but unnecessarily challenging. Bash loops, with their simple syntax and versatile application, turn this mountain into a molehill. In this section, we’ll dive into the essence of Bash loops, exploring their types, how they work, and why they’re an indispensable part of scripting in Linux environments.

The for loop is your go-to when you know how many times you want to repeat an action. It’s like saying, “For each item in this list, do this task.” Bash for loops iterate over a list of items or a range of values, executing commands for each item. Here’s the basic for loop syntax:

for variable in list
do
command1
command2
...
done

Notice that the for loop starts with a syntax that looks like “for this one item in a list of items.” In the case of a file, this could be for $line in lines. This statement initializes the loop. Next, you have the do keyword, followed by the loop statements, ending finally with done.

Imagine that you have a folder that contains some text files and you want to print their names:

for file in *.txt
do
echo "Text file: $file"
done

This loop goes through each file with a .txt extension in the current directory, assigning the filename to the file variable before printing it out using the echo statement.

When you’re writing a simple script such as the one shown here, it’s usually easier to make this a one-liner by separating each section using a semicolon, as shown here:

~ $ for file in *.txt;do echo "Text file: $file";done
Text file: example.txt
Text file: sample.txt

Note that for loops are sometimes used with a sequence. The Bash sequence expression generates a range of integers or characters. You define the start and end points of the range of integers or characters. A sequence consists of a range of values in curly brackets. This sequence takes the form of {START..END[..INCREMENT]}. If INCREMENT isn’t provided, it is 1 by default. A sequence is generally used in combination with for loops. Here’s a simple example:

~ $ for n in {1..5};do echo "Current value of n: $n";done
Current value of n: 1
Current value of n: 2
Current value of n: 3
Current value of n: 4
Current value of n: 5
~ $ for n in {a..d};do echo "Current value of n: $n";done
Current value of n: a
Current value of n: b
Current value of n: c
Current value of n: d

Now that you’ve learned about for loops, let’s move on and explore while loops.

Use a while loop when you want to repeat a task until a certain condition is no longer true. It’s like saying, “While this is true, keep going.” Here’s the basic syntax of a while loop:

while [ condition ]
do
command1
command2
...
done

Here’s an example where we create a countdown from 5:

#!/usr/bin/env bash
count=5
while [ $count -gt 0 ]
do
echo "Countdown: $count"
count=$((count-1))
done

This example code can be found in the ch03_loops_01.sh file in this chapter’s folder.

In this example, we initialize the count variable to 5. Then, we check the value of count; if it’s greater than 0, we print the value and then decrement the value by 1. The loop continues to run, so long as count is greater than 0. Each iteration decreases count by 1 until it is 0.

Running this script results in the following output:

~ $ bash ch03_loops_01.sh
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1

The most common way I use while loops is to read host names or IP addresses from a file and perform some operation on them. Sometimes, pentesting tools perform some operation on a single host and I want to run them across a list of hosts. Here’s a quick example where I use a one-line script with a while loop to read IP addresses from a file:

Figure 3.1 – Demonstrating a one-line while loop

I’ll explain this in more detail shortly.

Another example is the PetitPotam tool, which is used for coercing password hashes from unpatched Windows hosts. You can find more information about this and download the tool from https://github.com/topotam/PetitPotam. This tool accepts only one target host. Here, I’ve run it against a file containing a list of hosts using the following command:

Figure 3.2 – Demonstrating a one-line while loop with PetitPotam

The contents of the preceding screenshot can be explained as follows:

  • while read line: The while keyword ensures that we continue performing the loop until the condition is no longer true. In this case, we continue looping until it has reached the end of the file. The read keyword reads one line up until the newline from standard input (stdin) and assigns the data read to a variable named line. The read command returns a non-zero (false) status when it reaches the end of the file, causing the loop to terminate.
  • In Bash scripting, semicolons (;) are used to separate multiple commands on the same line. This allows you to write concise, one-line scripts where multiple commands are executed sequentially.
  • do python3 PetitPotam.py 10.2.10.99 $line: In Bash scripting, the do keyword marks the beginning of the block of commands to be executed in each iteration of a loop. In this case, it’s running the PetitPotam command. The first IP address, 10.2.10.99, is my Kali host IP address. The $line variable is the line of data that’s been read from the file. This becomes the target IP address for the PetitPotam command.
  • done: In Bash scripting, the done keyword marks the end of the block of commands that are executed in each iteration of a loop.
  • < ips.txt: I’m redirecting the content of the ips.txt file to stdin to be read by the read command. This file contains a list of IP addresses, with one address on each line.

Before running the PetitPotam command, I ran Responder in another Terminal tab using the sudo responder -I eth0 command. Responder is a rogue server that’s designed to elicit authentication from victims. Make sure you replace the IP address with your own if you’re performing this exercise. In the Responder output, I found that I captured a password hash from a vulnerable system:

Figure 3.3 – A password hash has been captured from the victim

Without the Bash while loop, I would have had to run the command manually for each host on the network. If I were testing a large network, this could be very tiring and I would have wasted a lot of time had I not harnessed the power of Bash!

Now that you’ve learned the power of while loops, let’s look at its alter-ego, the until loop.

The until loop is the opposite of the while loop. It keeps running until a condition becomes true. Think of it as, “Until this happens, do that.”

The basic syntax of the until loop is shown here:

until [ condition ]
do
command1
command2
...
done

Suppose you’re waiting for a file named done.txt to appear in the current directory:

#!/usr/bin/env bash
until [ -f done.txt ]
do
echo "Waiting for done.txt..."
sleep 1
done

This example code can be found in the ch03_loops_02.sh file in this chapter’s folder.

This loop runs until done .txt exists, checking every second.

I rarely use the until loop; however, it is very particular in some circumstances when you want to do something until a condition is true.

Next, we’ll explore how to use select to build interactive menus!

Another lesser-known loop command is select. It’s perfect for creating simple interactive menus in your scripts. With select, users can choose from options presented to them, making it ideal for navigation or settings menus:

#!/usr/bin/env bash
echo "What's your favorite programming language?"
select lang in Python Bash Ruby "C/C++" Quit; do
case $lang in
Python) echo "Great choice! Python is versatile." ;;
Bash) echo "Bash is great for shell scripting and automation!" ;;
Ruby) echo "Ruby is used in the Metasploit Framework." ;;
"C/C++") echo "C/C++ is powerful for system-level programming." ;;
Quit) break ;;
*) echo "Invalid option. Please try again." ;;
esac
done

This example code can be found in the ch03_loops_03.sh file in this chapter’s folder.

This script presents a list of programming languages and executes commands based on the user’s selection. The select command automatically creates a numbered menu, and the user inputs the number corresponding to their choice. Notice that each option must end with two semicolon (;;) characters. The *) expression is a fall-through that catches anything that’s entered that doesn’t match the previous choices.

Here’s what it looks like when you run it:

~ $ bash ch03_loops_03.sh
What's your favorite programming language?
1) Python
2) Bash
3) Ruby
4) C/C++
5) Quit
#? 2
Bash is great for shell scripting and automation!

Notice that when you run it, it continues to loop forever until you enter 5 for Quit, which uses the break statement in the code. The break statement breaks out of the loop. The break statement can be used in any loop to exit the loop, regardless of the conditional statement return value.

Now that you have a firm grasp of using loops, let’s explore some advanced examples.

You can nest loops within each other and use the break and continue keywords to control the flow more precisely. Here’s an example that prints a simple pattern:

#!/usr/bin/env bash
for i in {1..3}
do
for j in {1..3}
do
echo -n "$i$j "
done
echo "" # New line after each row
done

This example code can be found in the ch03_loops_04.sh file in this chapter’s folder.

This script prints a 3x3 grid of numbers, showing how nested loops work:

~ $ bash ch03_loops_04.sh
11 12 13
21 22 23
31 32 33

Next, let’s explore how the break and continue keywords can be used to help us use advanced logic in nested loops.

The break command completely exits the loop, while the continue command skips the rest of the current loop and starts the next iteration. The following example combines break and continue to demonstrate these concepts:

#!/usr/bin/env bash
for i in {1..20}; do
if ! [[ $(($i%2)) == 0 ]]; then
continue
elif [[ $i -eq 10 ]]; then
break
else echo $i
fi
done

This example code can be found in the ch03_loops_05.sh file in this chapter’s folder.

In the preceding example, a for loop iterates over a sequence of 1 to 20. Next, I introduce the modulus operator, %, which results in the remainder of a division operation. If the remainder isn’t zero, it continues to the next iteration of the loop. If the value of i equals 10, it breaks out of the loop. Otherwise, it prints the value of i. Here’s the result of running this code:

~ $ bash ch03_loops_05.sh
2
4
6
8

As you would expect, it prints all even numbers and exits when it reaches 10.

Bash loops are a fundamental part of scripting that can simplify and automate repetitive tasks. Whether you’re iterating over files, waiting for conditions, or creating interactive menus, understanding these loops can significantly enhance your scripting prowess. Start small, experiment with examples, and soon you’ll be looping like a pro!

In the next section, you’ll combine what you learned previously with a new concept: arrays.

One of the powerful features of Bash scripting is the use of arrays. Arrays allow you to store multiple values in a single variable, making your scripts more efficient and your code cleaner. Let’s dive into the basics of Bash arrays and explore how they can be utilized through practical examples.

At its core, an array is a collection of elements that can be accessed by an index. Think of it as a row of mailboxes, each with a unique number. You can store different pieces of mail (data) in each mailbox (element) and retrieve them using their mailbox number (index).

In Bash, arrays are incredibly flexible. They don’t require you to declare a type, and they can grow or shrink as needed. This means you can add or remove elements without having to worry about the size of the array.

Declaring an array in Bash is straightforward. You don’t need to explicitly declare a variable as an array; simply assigning values to it in an array context does the job. Here’s a simple example:

my_array=(apple banana cherry)

This line creates an array named my_array with three elements: apple, banana, and cherry.

To access an element in an array, you must use the following syntax:

${array_name[index]}

Remember, array indices in Bash start at 0. So, to access the first element (apple) in my_array, you would use the following syntax:

${my_array[0]}

Adding elements to an array or modifying existing ones is just as simple. To add an element to the end of the array, you can use the following syntax:

my_array+=(date)

The += operator is common to many programming languages. This operation says my_array is equal to the current value of my_array plus date.

Now, my_array contains four elements: apple, banana, cherry, and date. To modify an existing element, you must directly assign a new value to it:

my_array[1]=blueberry

This command changes the second element from banana to blueberry.

Looping through arrays is a common task in scripting. Here’s how you can iterate over each element in my_array:

#!/usr/bin/env bash
my_array=(apple banana cherry)
for fruit in "${my_array[@]}"
do
echo "Fruit: $fruit"
done

This example code can be found in the ch03_arrays_01.sh file in this chapter’s folder.

This loop prints each element in the array on a new line, as shown here:

~ $ bash ch03_arrays_01.sh
Fruit: apple
Fruit: banana
Fruit: cherry

Bash also supports associative arrays (sometimes called hash maps or dictionaries), where each element is identified by a key instead of a numeric index. To declare an associative array, use the -A flag with the declare keyword:

#!/usr/bin/env bash
# Declare the associative array.
declare -A my_assoc_array
# Assign new keys/value pairs to the associative array.
my_assoc_array[apple]="green"
my_assoc_array[banana]="yellow"
my_assoc_array[cherry]="red"
# The whole associative array is accessed as follows:
for key in "${!my_assoc_array[@]}"
do
# A key/value pair is accessed as shown:
echo "$key: ${my_assoc_array[$key]}"
done

This example code can be found in the ch03_arrays_02.sh file in this chapter’s folder.

Accessing and modifying elements in an associative array works similarly to indexed arrays, but you use keys instead of numeric indices.

In the preceding script, the associative array is declared by using declare -A and the array’s name. Then, key/value pairs are added to the associative array. Next, the for loop uses the key variable to access each loop in the array.

Important note

You can refer to the whole associative array using "${!my_assoc_array[@]}".

Finally, during each iteration of the for loop, the current key/value pair is printed:

~ $ bash ch03_arrays_02.sh
cherry: red
apple: green
banana: yellow

You may have noticed that associative arrays in Bash don’t maintain order; they’re unordered collections of key/value pairs. This is why the key/value pairs were printed in a different order than the order they were added to the array.

You can access the value of a specific associative array key/value pair using the following syntax:

{my_assoc_array[key]}

The following script shows the same code as the previous script with this concept added on the last line:

#!/usr/bin/env bash
# Declare the associative array.
declare -A my_assoc_array
# Assign new keys and values to the associative array.
my_assoc_array[apple]="green"
my_assoc_array[banana]="yellow"
my_assoc_array[cherry]="red"
# The whole associative array is accessed as follows:
for key in "${!my_assoc_array[@]}"
do
# A key/value pair is accessed as shown:
echo "$key: ${my_assoc_array[$key]}"
done
# Access a specific value from the associative array:
echo "The color of an apple is: ${my_assoc_array[apple]}"

This example code can be found in the ch03_arrays_03.sh file in this chapter’s folder.

The output of this script is as follows:

~ $ bash ch03_arrays_03.sh
cherry: red
apple: green
banana: yellow
The color of an apple is: green

Bash arrays are a powerful feature that can make your scripts more efficient and easier to read. Whether you’re storing a simple list of items or dealing with more complex data structures, such as associative arrays, understanding how to work with arrays will significantly enhance your scripting capabilities. Remember, practice is key to mastering Bash arrays, so don’t hesitate to experiment with the examples provided and explore further applications on your own.

This concludes a closely related set of topics. Bash variables, conditionals, loops, and arrays are tools in Bash scripting for storing data, making decisions, repeating tasks, and handling lists of values, respectively.

The loop is the star of the show. Just like the cast of any show, they require a supporting cast. In the case of loops, they require variables to assign labels to data, conditionals to test equality, and arrays to store data. Together, they work as a team and make your Bash scripts much more powerful and flexible.

In the next chapter, you’ll learn about Bash regular expressions, a valuable skill that you’ll need to master to search and match text effectively.