Bash

๐Ÿงพ Bash Syntax โ€“ The Basics

Start of a script:

#!/bin/bash

Basic Syntax Rules:

Example:

#!/bin/bash
echo "Hello, Bash!"

Run with:

./script.sh

๐Ÿ“œ Bash Script โ€“ Writing Your First Script

Steps:

  1. Create file: nano hello.sh
  2. Add:
    #!/bin/bash
    echo "Hello World"
    
  3. Make executable: chmod +x hello.sh
  4. Run: ./hello.sh

Multiline Example:

#!/bin/bash
name="Kashif"
echo "Welcome, $name"
date

๐Ÿ”ก Bash Variables โ€“ Store and Use Data

Declare:

name="Kashif"

Access:

echo $name

Rules:

Example:

#!/bin/bash
user="kashif"
echo "Welcome $user"

๐Ÿ—‚๏ธ Bash Data Types (Implicit)

Bash supports:

Examples:

name="Kashif"        # String
age=20             # Integer

let age=age+1
echo $age

arr=(one two three)  # Array
echo ${arr[0]}

โž• Bash Operators

Arithmetic:

a=5
b=3
echo $((a + b))

Comparison:

| Operator | Description | |โ€”โ€”โ€”-|โ€”โ€”โ€”โ€”โ€”โ€”-| | -eq | Equal | | -ne | Not equal | | -gt | Greater than | | -lt | Less than | | -ge | Greater or equal | | -le | Less or equal |

Example:

if [ $a -gt $b ]; then
  echo "a > b"
fi

๐Ÿ”€ Bash Ifโ€ฆElse

Syntax:

if [ condition ]; then
   commands
elif [ condition ]; then
   commands
else
   commands
fi

Examples:

#!/bin/bash
num=10

if [ $num -gt 5 ]; then
  echo "Greater than 5"
else
  echo "5 or less"
fi

๐Ÿ” Bash Loops

for Loop:

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

while Loop:

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

until Loop:

n=1
until [ $n -gt 3 ]; do
  echo "Until $n"
  ((n++))
done

๐Ÿ”ฃ Bash Functions

Define:

function_name () {
  commands
}

Call:

function_name

Example:

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

greet "Kashif"

$1, $2 = arguments to the function


๐Ÿงฎ Bash Arrays

Declare:

arr=(apple banana cherry)

Access:

echo ${arr[1]}     # banana

Loop through array:

for item in "${arr[@]}"; do
  echo $item
done

Array length:

echo ${#arr[@]}

โฐ Bash Schedule (Cron Jobs)

Syntax:

* * * * * command
โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ Day of Week (0-7)
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€ Month (1-12)
โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€ Day of Month (1-31)
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Hour (0-23)
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Minute (0-59)

Edit Crontab:

crontab -e

Example:

0 6 * * * /home/user/backup.sh

Runs daily at 6:00 AM.

List cron jobs:

crontab -l