Your First Bash Script
Creating a script
#!/bin/bash
# This is a comment
echo "Hello from my first script!"
echo "Today is: $(date)"
echo "You are: $(whoami)"
The shebang line
#!/bin/bash — the first line tells the system which interpreter to use.
Common shebangs:
#!/bin/bash # Bash script
#!/usr/bin/env bash # Portable bash
#!/bin/sh # POSIX sh (more portable)
#!/usr/bin/python3 # Python script
Making it executable
chmod +x myscript.sh
./myscript.sh
Running without execute permission
bash myscript.sh
sh myscript.sh
Script structure best practices
#!/bin/bash
# Script: backup.sh
# Description: Backup home directory
# Author: IVski
# Date: 2024
set -e # Exit on error
set -u # Error on undefined variables
set -o pipefail # Catch pipe errors
# Variables
SRC_DIR="$HOME"
BACKUP_DIR="/tmp/backup"
DATE=$(date +%Y%m%d)
# Main logic
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/backup-$DATE.tar.gz" "$SRC_DIR"
echo "Backup created: $BACKUP_DIR/backup-$DATE.tar.gz"