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.
#!/bin/bash
# This is a comment
name="John"
echo "Hello, $name"
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
age=20
if [ "$age" -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
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
for var in list; do
commands
done
for i in 1 2 3; do
echo "Number $i"
done
while [ condition ]; do
commands
done
count=1
while [ $count -le 5 ]; do
echo "Count $count"
((count++))
done
until [ condition ]; do
commands
done
function_name() {
commands
}
greet() {
echo "Hello, $1"
}
greet "Alice"
function_name() {
return value
}
Note: You can only return numbers (0–255). Use output (stdout) for other data.
read variable_name
echo "Enter your name:"
read name
echo "Hello, $name"
command > file # overwrite
command >> file # append
command 2> file # stderr
command &> file # stdout & stderr
command1 | command2
-e filename
— exists-d filename
— directory-f filename
— regular file-r filename
— readable-w filename
— writable-x filename
— executableif [ -e "file.txt" ]; then
echo "File exists"
fi
=
— equal!=
— not equal-z
— empty-n
— not emptystr="Hello"
if [ "$str" = "Hello" ]; then
echo "Match!"
fi
let result=1+2
echo $result
result=$((1+2))
echo $result
result=$(expr 1 + 2)
echo $result
arr=(one two three)
echo ${arr[0]}
echo ${arr[@]}
echo ${#arr[@]}
$#
— number of args$0
— script name$1, $2, …
— positional params$@
— all args$$
— PID$?
— last exit status#!/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"
#!/bin/bash
ping -c 1 google.com &> /dev/null
if [ $? -eq 0 ]; then
echo "Internet is up"
else
echo "Internet is down"
fi