Introduction

Bash (Bourne Again SHell) is a powerful scripting language built on top of the original Unix shell (sh). It's used to automate tasks, manage systems, and quickly build powerful workflows.

1. Basic Syntax

1.1 Shebang

#!/bin/bash

1.2 Comments

# This is a comment

1.3 Variables

name="John"
echo "Hello, $name"

2. Control Structures

2.1 If Statements

if [ condition ]; then
    commands
elif [ condition ]; then
    commands
else
    commands
fi
age=20
if [ "$age" -ge 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

2.2 Case Statement

case "$variable" in
    pattern1) commands ;;
    pattern2) commands ;;
    *) default ;;
esac
day="Monday"
case $day in
    "Monday") echo "Start of week" ;;
    "Friday") echo "End of week" ;;
    *) echo "Midweek" ;;
esac

2.3 Loops

For Loop

for var in list; do
    commands
done
for i in 1 2 3; do
    echo "Number $i"
done

While Loop

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

Until Loop

until [ condition ]; do
    commands
done

3. Functions

3.1 Defining & Calling

function_name() {
    commands
}
greet() {
    echo "Hello, $1"
}

greet "Alice"

3.2 Returning Values

function_name() {
    return value
}

Note: You can only return numbers (0–255). Use output (stdout) for other data.

4. Input & Output

4.1 read – User Input

read variable_name
echo "Enter your name:"
read name
echo "Hello, $name"

4.2 Redirecting Output

command > file      # overwrite
command >> file     # append
command 2> file     # stderr
command &> file     # stdout & stderr

4.3 Pipes

command1 | command2

5. File Test Operators

if [ -e "file.txt" ]; then
    echo "File exists"
fi

6. String Operators

str="Hello"
if [ "$str" = "Hello" ]; then
    echo "Match!"
fi

7. Arithmetic Operations

7.1 let

let result=1+2
echo $result

7.2 $(( ))

result=$((1+2))
echo $result

7.3 expr

result=$(expr 1 + 2)
echo $result

8. Arrays

8.1 Declaring

arr=(one two three)

8.2 Accessing Elements

echo ${arr[0]}

8.3 All Elements

echo ${arr[@]}

8.4 Length

echo ${#arr[@]}

9. Special Variables

10. Practical Examples

10.1 Backup Script

#!/bin/bash

src="/path/to/source"
dest="/path/to/backup-$(date +%Y%m%d%H%M%S)"

cp -r "$src" "$dest"
echo "Backup completed: $dest"

10.2 Internet Check

#!/bin/bash

ping -c 1 google.com &> /dev/null

if [ $? -eq 0 ]; then
    echo "Internet is up"
else
    echo "Internet is down"
fi