Start of a script:
#!/bin/bash
Basic Syntax Rules:
#
for commentschmod +x script.sh
Example:
#!/bin/bash
echo "Hello, Bash!"
Run with:
./script.sh
Steps:
nano hello.sh
#!/bin/bash
echo "Hello World"
chmod +x hello.sh
./hello.sh
Multiline Example:
#!/bin/bash
name="Kashif"
echo "Welcome, $name"
date
Declare:
name="Kashif"
Access:
echo $name
Rules:
=
$
to reference valueExample:
#!/bin/bash
user="kashif"
echo "Welcome $user"
Bash supports:
let
or $(( ))
)Examples:
name="Kashif" # String
age=20 # Integer
let age=age+1
echo $age
arr=(one two three) # Array
echo ${arr[0]}
a=5
b=3
echo $((a + b))
| 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
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
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
Define:
function_name () {
commands
}
Call:
function_name
Example:
greet() {
echo "Hello, $1"
}
greet "Kashif"
$1
,$2
= arguments to the function
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[@]}
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