Write bash scripts with variables, conditionals, loops, and functions. Automate backups and deployments.
#!/bin/bash
# The shebang tells the OS to use bash
set -euo pipefail # exit on error, undefined var, pipe failure
# Variables (no spaces around =)
NAME="World"
echo "Hello, $NAME!"
echo "Script: $0, Arg1: $1, All args: $@"
# Command substitution
TODAY=$(date +%Y-%m-%d)
FILE_COUNT=$(ls | wc -l)
echo "Today: $TODAY, Files: $FILE_COUNT"# if/elif/else
if [ -f "file.txt" ]; then
echo "File exists"
elif [ -d "mydir" ]; then
echo "Directory exists"
else
echo "Neither exists"
fi
# for loop
for file in *.txt; do
echo "Processing: $file"
done
# while loop
COUNT=0
while [ $COUNT -lt 5 ]; do
echo "Count: $COUNT"
COUNT=$((COUNT + 1))
done#!/bin/bash
set -euo pipefail
# Function
backup() {
local SRC=$1
local DST=$2
local DATE=$(date +%Y%m%d_%H%M%S)
cp -r "$SRC" "${DST}_${DATE}"
echo "Backed up $SRC to ${DST}_${DATE}"
}
# Error handling
if ! command -v docker &>/dev/null; then
echo "Error: Docker not installed" >&2
exit 1
fi
# Run backup
backup /var/www/html /backup/html# Edit crontab
crontab -e
# Format: minute hour day month weekday command
# Run backup every day at 2am
0 2 * * * /home/bo/scripts/backup.sh >> /var/log/backup.log 2>&1
# Every 15 minutes
*/15 * * * * /home/bo/scripts/check-disk.sh
# Every Monday at 9am
0 9 * * 1 /home/bo/scripts/weekly-report.sh#!/bin/bash shebang + set -euo pipefail at the top of every script.=. Reference with $NAME or ${NAME}.[ -f file ] tests file existence. [ -d dir ] for directories. [ $a -eq $b ] for numbers.