Bash Variables and Arrays - Assignment, Export, Arrays, Scope

Learn bash variable assignment, environment variables, indexed and associative arrays, variable scope, and special shell variables with practical examples.

Variables

Detailed Explanation

Variables and Arrays in Bash

Variables store data for use throughout a script. Bash supports simple variables, indexed arrays, and associative arrays (bash 4+).

Variable Assignment

# Basic assignment (no spaces around =)
NAME="Alice"
COUNT=42
TODAY=$(date +%Y-%m-%d)

# Read-only variables
readonly VERSION="2.0.0"
VERSION="3.0.0"  # Error: readonly variable

# Unset a variable
unset TEMP_VAR

Environment Variables

Variables are local to the current shell by default. Use export to make them available to child processes:

export DATABASE_URL="postgres://localhost/mydb"
export PATH="$PATH:/usr/local/bin"

# Set for a single command
NODE_ENV=production node server.js

Special Variables

$0    # script name
$1-$9 # positional arguments
$#    # number of arguments
$@    # all arguments (individually quoted)
$?    # exit status of last command
$$    # PID of current shell
$!    # PID of last background process

Indexed Arrays

# Declaration
FRUITS=("apple" "banana" "cherry" "date")

# Access
echo ${FRUITS[0]}      # apple
echo ${FRUITS[@]}      # all elements
echo ${#FRUITS[@]}     # array length (4)

# Append
FRUITS+=("elderberry")

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

# Slice
echo ${FRUITS[@]:1:2}  # banana cherry

Associative Arrays (Bash 4+)

declare -A CONFIG
CONFIG[host]="localhost"
CONFIG[port]="3000"
CONFIG[env]="production"

# Access
echo ${CONFIG[host]}

# All keys
echo ${!CONFIG[@]}     # host port env

# Iterate
for key in "${!CONFIG[@]}"; do
  echo "$key = ${CONFIG[$key]}"
done

# Check if key exists
if [[ -v CONFIG[host] ]]; then
  echo "host is set"
fi

Variable Scope

# Global (default)
GLOBAL_VAR="I'm global"

my_function() {
  local LOCAL_VAR="I'm local"
  echo $GLOBAL_VAR    # accessible
  echo $LOCAL_VAR     # accessible
}

my_function
echo $LOCAL_VAR       # empty (not accessible outside function)

Practical Patterns

# Configuration with defaults
DB_HOST=${DB_HOST:-localhost}
DB_PORT=${DB_PORT:-5432}
DB_NAME=${DB_NAME:?"DB_NAME is required"}

# Build connection string
CONNECTION="postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}"

Use Case

Variables and arrays are fundamental to every bash script. They are used for storing configuration values, processing command-line arguments, building dynamic commands, managing lists of items (servers, files, users), and passing data between functions. Understanding variable scope and export is critical for writing scripts that interact with other processes.

Try It — Bash Cheat Sheet

Open full tool