# Bash Loops and Conditionals

[Bash](https://www.gnu.org/software/bash/), the default shell in many Linux distributions, offers powerful constructs for controlling program flow. This post focuses on two fundamental elements: `if` statements for conditional execution and `for` loops for iterative processing. Mastering these will significantly enhance your shell scripting abilities.

## The `if` Statement

The [`if`](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html) statement allows you to execute commands conditionally. Its basic structure involves a test condition followed by one or more commands that are executed if the condition evaluates to true. A simple example might look like this:

```bash
#!/bin/bash

number=10

if [ $number -gt 5 ]; then
    echo "The number is greater than 5"
fi
```

This script checks if the variable `number` is greater than 5. The `-gt` operator performs the numerical comparison. If true, the message is printed. The `fi` keyword marks the end of the `if` block. More complex conditions can be created using `elif` (else if) and `else` clauses.

## The `for` Loop

[`for`](https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html) loops are ideal when you need to execute a block of code multiple times. Bash offers several ways to use `for` loops, including iterating over a sequence of numbers or a list of words. A common pattern iterates over a set of files:

```bash
#!/bin/bash

for file in *.txt; do
    echo "Processing file: $file"
done
```

This script processes all files ending in `.txt` in the current directory. Each filename is assigned to the variable `file` in each iteration, and the `done` keyword marks the end of the loop. Another way to use the for loop is by using an array:

```bash
#!/bin/bash

myArray=(
    "apple"
    "banana"
    "cherry"
)

for i in "${myArray[@]}"; do 
    echo "item is: $i"
done
```

Output:

```plaintext

item is: apple
item is: banana
item is: cherry
```

## Further Reading

To delve deeper, explore Bash's [`case`](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html) statement for multiple-condition decision-making and the [`while`](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_02.html) and [`until`](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_03.html) loops for conditions that are checked before and after each iteration, respectively. The Bash manual provides comprehensive documentation on these and other control flow structures.
