Bash Script Basics - Shebang, Arguments, Exit Codes, set Options

Essential bash scripting fundamentals including shebang lines, command-line argument parsing, exit codes, set options for safety, and script structure best practices.

Script Basics

Detailed Explanation

Bash Script Basics

Writing robust bash scripts requires understanding fundamental concepts like the shebang line, argument handling, exit codes, and safety options.

The Shebang Line

Every bash script should start with a shebang that specifies the interpreter:

#!/bin/bash           # absolute path (most common)
#!/usr/bin/env bash   # portable (finds bash in PATH)

Making Scripts Executable

chmod +x script.sh
./script.sh

Safety Options

Always use these at the top of your scripts:

#!/usr/bin/env bash
set -euo pipefail

# -e  Exit immediately if a command fails
# -u  Treat unset variables as errors
# -o pipefail  Fail if any command in a pipe fails

Command-Line Arguments

#!/usr/bin/env bash
set -euo pipefail

# Check argument count
if [ $# -lt 1 ]; then
  echo "Usage: $0 <environment> [--force]"
  exit 1
fi

ENVIRONMENT="$1"
FORCE=false

# Parse flags
for arg in "$@"; do
  case "$arg" in
    --force) FORCE=true ;;
  esac
done

echo "Deploying to $ENVIRONMENT (force=$FORCE)"

Exit Codes

# Convention:
# 0     success
# 1     general error
# 2     misuse of command
# 126   permission denied
# 127   command not found
# 128+N killed by signal N

exit 0    # success
exit 1    # failure

Script Template

#!/usr/bin/env bash
set -euo pipefail

# Constants
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"

# Functions
usage() {
  cat << EOF
Usage: $SCRIPT_NAME [options] <argument>

Options:
  -h, --help    Show this help message
  -v, --verbose Enable verbose output
  -f, --force   Force operation

Arguments:
  argument      Description of the argument
EOF
}

log() {
  echo "[$(date '+%H:%M:%S')] $*"
}

# Parse arguments
VERBOSE=false
FORCE=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h|--help) usage; exit 0 ;;
    -v|--verbose) VERBOSE=true; shift ;;
    -f|--force) FORCE=true; shift ;;
    *) break ;;
  esac
done

# Main logic
log "Starting $SCRIPT_NAME"
# ... your code here ...
log "Done"

Trap for Cleanup

TEMP_DIR=$(mktemp -d)

cleanup() {
  rm -rf "$TEMP_DIR"
  log "Cleaned up temporary files"
}

trap cleanup EXIT ERR

Use Case

Every bash script benefits from proper structure and safety options. The set -euo pipefail combination catches the majority of common scripting errors. A well-structured script template with argument parsing, usage messages, and cleanup traps saves time and prevents bugs in deployment scripts, automation tools, and system administration tasks.

Try It — Bash Cheat Sheet

Open full tool