TutsFx logo

Bash Scripting Basics

Conditionals and Loops

2 min read Last updated 1 hour ago

Decision-making and repetition turn scripts into real programs.

The if statement

bash
#!/bin/bash

file="notes.txt"

if [ -f "$file" ]; then
    echo "$file exists"
else
    echo "$file does not exist"
fi

The [ ... ] is the test command. Common tests:

Test True when
-f file file exists and is a regular file
-d dir dir exists and is a directory
-e path the path exists (any type)
$a -eq $b numbers are equal (-ne, -gt, -lt also exist)
"$a" = "$b" strings are equal (!= for not equal)
!

Quote your variables

Always wrap variables in quotes inside tests: [ "$name" = "Ada" ]. Unquoted empty variables can make the test fail or misbehave.

The for loop

bash
#!/bin/bash

for name in Ada Grace Alan; do
    echo "Hello, $name"
done

A very common pattern — act on every .txt file:

bash
for file in *.txt; do
    echo "Processing $file"
    wc -l "$file"
done

The while loop

bash
#!/bin/bash

count=1
while [ "$count" -le 5 ]; do
    echo "Count: $count"
    count=$((count + 1))
done

$(( ... )) performs arithmetic.

Putting it together

bash
#!/bin/bash
# Report the size of every log file

for file in /var/log/*.log; do
    if [ -f "$file" ]; then
        size=$(du -h "$file" | cut -f1)
        echo "$file  ->  $size"
    fi
done

Try it

  1. Write a loop that prints 1 to 10
  2. Extend it to print only even numbers (hint: test $((n % 2)) -eq 0)
  3. Write a script that checks whether a directory passed as $1 exists
Share:

We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads, and analyze traffic. By clicking "Accept", you consent to our use of cookies. Read our Privacy Policy to learn more.