Bash

Bash

Shebang

The shebang line tells the system which interpreter to use to execute the script:

#!/bin/bash

Variables

Define and use variables:

name="Bob"
echo "Hello world, $name!"

User input

Read user input:

echo "What is your name?"
read name
echo "Hello, $name!"

For loop

Iterate through a range:

for i in {1..5}; do
    echo "Number $i"
done

Conditional statements

Use conditional logic:

echo "Enter a number:"
read num
if [ $num -lt 10 ]; then
    echo "The number is less than 10."
else
    echo "The number is 10 or greater."
fi

Comparison operators:

  • -lt for “less than”

  • -gt for “greater than”

  • -eq for “equals”

  • -ne for “not equal”

  • -le for “less than or equal to”

  • -ge for “greater than or equal to”

While loop

Loop while a condition is true:

counter=1
while [ $counter -le 5 ]; do
    echo "Counter is $counter"
    ((counter++))
done

Functions

Define and call functions:

intro() {
    echo "Hi $1! You are $2 years old."
}
intro "Bob" 30

Folder and file management

Loop through directories with argument validation:

# $# is a special variable giving the number of arguments
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 /path/to/directory"
    exit 1
fi

# Use the first argument as the root directory
root_dir="$1/*"

# Loop through each item in the root directory
for dir in $root_dir; do
    if [ -d "$dir" ]; then  # Check if it's a directory
        echo "Visiting directory: $dir"
        # Perform operations in "$dir"
    fi
done

To use, run:

./script.sh /path/to/directory

Verify a file exists before proceeding:

# Check if a file exists
if [ ! -f "my_file.txt" ]; then
    echo "Error: File does not exist."
    exit 1
fi

Note

exit 1 (or any non-zero value) indicates that the script terminated with an error. A successful script should exit 0 or simply exit without a code.

Common file test operators

  • -f file - True if file exists and is a regular file

  • -d dir - True if dir exists and is a directory

  • -e path - True if path exists (file or directory)

  • -r file - True if file exists and is readable

  • -w file - True if file exists and is writable

  • -x file - True if file exists and is executable