Home/Engineer/Linux / Shell/Advanced Bash Scripting — Fu…
Linux / ShellIntermediateUbuntuDebianCentOSmacOSbashshell

Advanced Bash Scripting — Functions, Arrays, getopts, and trap

A practical roundup of production automation patterns: function definitions and return values, array manipulation, option parsing with getopts, and signal handling with trap.

Contents
  1. Function Definitions and Return Values
  2. Array Manipulation
  3. Parsing Options with getopts
  4. Signal Handling with trap
  5. Production Patterns
  6. Creating Config Files with Heredoc

Function Definitions and Return Values

Bash
# Basic function
greet() {
  local name="$1"          # Restrict scope with local
  echo "Hello, $name"
}
greet "World"

# Return value (exit-code style)
is_root() {
  [[ $EUID -eq 0 ]]        # 0 is true, 1 is false
}
if is_root; then echo "running as root"; fi

# Return a value via stdout
get_date() {
  date +%Y%m%d
}
TODAY=$(get_date)
echo "$TODAY"

Array Manipulation

Bash
# Declaration and access
fruits=("apple" "banana" "cherry")
echo "${fruits[0]}"          # apple
echo "${fruits[@]}"          # all elements
echo "${#fruits[@]}"         # length: 3

# Append and delete
fruits+=("grape")
unset fruits[1]              # remove banana

# Iterate
for fruit in "${fruits[@]}"; do
  echo "$fruit"
done

# Associative array (Bash 4+)
declare -A config
config[host]="localhost"
config[port]="5432"
echo "${config[host]}:${config[port]}"

Parsing Options with getopts

Bash
#!/usr/bin/env bash
usage() {
  echo "Usage: $0 [-h] [-n NAME] [-v]"
  exit 1
}

VERBOSE=false
NAME=""

while getopts ":hn:v" opt; do
  case $opt in
    h) usage ;;
    n) NAME="$OPTARG" ;;
    v) VERBOSE=true ;;
    :) echo "Option -$OPTARG requires an argument"; exit 1 ;;
    ?) echo "Unknown option: -$OPTARG"; exit 1 ;;
  esac
done
shift $((OPTIND - 1))       # remaining positional args

echo "Name: $NAME, Verbose: $VERBOSE"
echo "Remaining args: $*"

Signal Handling with trap

Bash
# Temp-file cleanup pattern
TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"; echo "Cleaned up"; exit' EXIT INT TERM

# Do work
echo "data" > "$TMPFILE"
sleep 10      # TMPFILE is deleted even if you press Ctrl+C

# Debug trace
trap 'echo "Line $LINENO: $BASH_COMMAND"' DEBUG

Production Patterns

Bash
# Strict mode (always recommended)
set -euo pipefail

# Colored output
RED='\033[0;31m'; GREEN='\033[0;32m'; NC='\033[0m'
echo -e "${GREEN}OK${NC} done"
echo -e "${RED}ERROR${NC} failed"

# Retry function
retry() {
  local n=0; local max=3; local delay=5
  until "$@"; do
    n=$((n+1))
    [[ $n -ge $max ]] && { echo "Failed after $max attempts"; return 1; }
    echo "Retry $n/$max in ${delay}s..."; sleep $delay
  done
}
retry curl -sf https://example.com

# Logging function
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a /var/log/myscript.log
}
log "Started"

Creating Config Files with Heredoc

Bash
cat > /etc/myapp/config.conf << EOF
host=${DB_HOST:-localhost}
port=${DB_PORT:-5432}
user=${DB_USER:-app}
EOF

# To write literally without variable expansion
cat > script.sh << 'EOF'
echo "$PATH"   # printed as-is (no expansion)
EOF
#bash#shell
Editorial note

AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us

Topic-related official docs (auto-linked · not per-claim sources)Linux man pages ↗

Questions & answers

Ask a question about this guide. We'll review and reply.