Variables, Conditionals, Loops, and Arrays
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
Technical requirements
Section titled “Technical requirements”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.
Introducing variables
Section titled “Introducing variables”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.
Declaring variables
Section titled “Declaring variables”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=valueFor 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 arg3Inside 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,$1through$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
Accessing variables
Section titled “Accessing variables”To access the value of a variable, you simply use the variable’s name preceded by a dollar sign, $:
#!/usr/bin/env bashmy_string="Welcome to Bash Scripting for Pentesters!"echo $my_stringThis 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 bashname=$1age=$2echo "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 25Hello 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 basha=5b=3c=$((a + b))let d=a+blet e=a*becho "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.sha = 5b = 3c = 8d = 83 = 15Now that you understand how to create and access variables, we’ll move on to a special type of variable, the environment variable.
Environment variables
Section titled “Environment variables”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_varAfter 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/programThis 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.
A review of variables
Section titled “A review of variables”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 variablesname=$1age=$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 fourthThe 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 fourthThe first argument is: first argThe second argument is: 2ndThe first and second arguments are: first arg 2ndNext, 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.shIn 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.shHere, 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 4Important 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.
Branching with conditional statements
Section titled “Branching with conditional statements”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
Section titled “The if statement”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 bashUSER="$1"if [ $USER == 'steve' ]; then echo "Welcome back, Steve!"fiThis 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!"; fiAdding else
Section titled “Adding else”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 bashUSER="$1"if [ $USER == 'steve' ]; then echo "Welcome back, Steve!"else echo "Access denied."fiThis 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 SomebodyAccess denied.The power of elif
Section titled “The power of elif”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 bashif [ $USER == 'steve' ]; then echo "Welcome back, Steve!"elif [ $USER == 'admin' ]; then echo "Hello, admin."else echo "Access denied."fiThis 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.shWelcome 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.
Beyond simple comparisons
Section titled “Beyond simple comparisons”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 bashif [ -f "/path/to/file.txt" ]; then echo "File exists. Proceeding with read operation."else echo "File does not exist. Aborting."fiThis 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 bashnum1=10num2=20# Compare if num1 is equal to num2if [ $num1 -eq $num2 ]; then echo "num1 is equal to num2"else echo "num1 is not equal to num2"fiThis 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 num2In 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 greaterThe following code demonstrates how to use the less than -lt operator to compare integers:
#!/usr/bin/env bashnum1=10num2=20if [ $num1 -lt $num2 ]; then echo "num1 is less than num2"else echo "num1 is not less than num2"fiThis 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 num2The following code demonstrates how to use the greater-than or equal-to operator, -ge:
#!/usr/bin/env bashnum1=10num2=20if [ $num1 -ge $num2 ]; then echo "num1 is greater than or equal to num2"else echo "num1 is not greater than or equal to num2"fiThis 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 num2String 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 emptySTRING1 == STRING2: True if the strings are equalSTRING1 != STRING2: True if the strings are not equal
Here’s an example demonstrating string comparisons:
#!/usr/bin/env bash# Declare string variablesstr1="Hello"str2="World"str3="Hello"# Compare if str1 is equal to str2if [ "$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 str3if [ "$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 str2if [[ "$str1" < "$str2" ]]; then echo "str1 is less than str2"else echo "str1 is not less than str2"fiThis 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 str2str1 is equal to str3str1 is less than str2This 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.
Combining conditions
Section titled “Combining conditions”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 bashif [ $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."fiThis 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.
Case statements
Section titled “Case statements”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/bashread -p "Enter your favorite fruit: " fruitcase $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." ;;esacThis 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.shEnter your favorite fruit: pearHmm, 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 inputt 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 onlyncharscharacters-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!
Repeating with loops
Section titled “Repeating with loops”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
Section titled “The for loop”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 listdo command1 command2 ...doneNotice 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 *.txtdo echo "Text file: $file"doneThis 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";doneText file: example.txtText file: sample.txtNote 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";doneCurrent value of n: 1Current value of n: 2Current value of n: 3Current value of n: 4Current value of n: 5~ $ for n in {a..d};do echo "Current value of n: $n";doneCurrent value of n: aCurrent value of n: bCurrent value of n: cCurrent value of n: dNow that you’ve learned about for loops, let’s move on and explore while loops.
The while loop
Section titled “The while loop”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 ...doneHere’s an example where we create a countdown from 5:
#!/usr/bin/env bashcount=5while [ $count -gt 0 ]do echo "Countdown: $count" count=$((count-1))doneThis 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.shCountdown: 5Countdown: 4Countdown: 3Countdown: 2Countdown: 1The 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: Thewhilekeyword 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. Thereadkeyword reads one line up until the newline from standard input (stdin) and assigns the data read to a variable namedline. Thereadcommand 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, thedokeyword marks the beginning of the block of commands to be executed in each iteration of a loop. In this case, it’s running thePetitPotamcommand. The first IP address,10.2.10.99, is my Kali host IP address. The$linevariable is the line of data that’s been read from the file. This becomes the target IP address for thePetitPotamcommand.done: In Bash scripting, thedonekeyword 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 theips.txtfile tostdinto be read by thereadcommand. 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
Section titled “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 ...doneSuppose you’re waiting for a file named done.txt to appear in the current directory:
#!/usr/bin/env bashuntil [ -f done.txt ]do echo "Waiting for done.txt..." sleep 1doneThis 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!
Select – interactive menus made easy
Section titled “Select – interactive menus made easy”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 bashecho "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." ;; esacdoneThis 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.shWhat's your favorite programming language?1) Python2) Bash3) Ruby4) C/C++5) Quit#? 2Bash 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.
Advanced usage – nested loops
Section titled “Advanced usage – nested loops”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 bashfor i in {1..3}do for j in {1..3} do echo -n "$i$j " done echo "" # New line after each rowdoneThis 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.sh11 12 1321 22 2331 32 33Next, let’s explore how the break and continue keywords can be used to help us use advanced logic in nested loops.
Using break and continue
Section titled “Using break and continue”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 bashfor i in {1..20}; do if ! [[ $(($i%2)) == 0 ]]; then continue elif [[ $i -eq 10 ]]; then break else echo $i fidoneThis 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.sh2468As 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.
Using arrays for data containers
Section titled “Using arrays for data containers”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]=blueberryThis command changes the second element from banana to blueberry.
Looping through arrays
Section titled “Looping through arrays”Looping through arrays is a common task in scripting. Here’s how you can iterate over each element in my_array:
#!/usr/bin/env bashmy_array=(apple banana cherry)for fruit in "${my_array[@]}"do echo "Fruit: $fruit"doneThis 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.shFruit: appleFruit: bananaFruit: cherryBash 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]}"doneThis 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.shcherry: redapple: greenbanana: yellowYou 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.shcherry: redapple: greenbanana: yellowThe color of an apple is: greenBash 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.
Summary
Section titled “Summary”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.