Variables in Scripts
Variables store values; assign with no spaces and read with a dollar sign.
Syntax
name=value
echo "$name"
result=$(command)Variables let a script remember values. The rules are strict but simple.
Assigning and reading
- Assign with no spaces around the
=:name="Alice". - Read the value by prefixing with
$:echo "$name". - Wrap uses in double quotes to be safe with spaces.
Command substitution
$(command) runs a command and inserts its output. For example today=$(date +%F) stores today's date.
Example
#!/bin/bash
greeting="Hello"
name="Alice"
echo "$greeting, $name!"
# Hello, Alice!
# Capture a command's output
today=$(date +%F)
files=$(ls | wc -l)
echo "On $today there are $files files here."When to use it
- A deployment script stores the release tag in a variable 'VERSION=v1.4.2' and uses it consistently across all file paths and log messages.
- A sysadmin script captures a command's output in a variable with 'DISK_FREE=$(df -h / | awk NR==2{print $4})' to use in an alert.
- A developer uses a readonly variable 'readonly DB_HOST=db.internal' to prevent accidental reassignment of critical config values in a script.
More examples
Assign and use variables
Shows variable assignment (no spaces around =) and expansion with ${} inside double-quoted strings.
#!/bin/bash
APP_NAME="myapp"
VERSION="2.1.0"
DEPLOY_DIR="/opt/${APP_NAME}"
echo "Deploying ${APP_NAME} v${VERSION} to ${DEPLOY_DIR}"Capture command output
Uses $() command substitution to capture command output into variables for use in messages or conditions.
#!/bin/bash
# Capture current date and free disk space
TODAY=$(date +%Y-%m-%d)
DISK_FREE=$(df -h / | awk 'NR==2 {print $4}')
echo "[$TODAY] Free space on /: $DISK_FREE"Default values and readonly
Uses ${VAR:-default} for fallback values and readonly to lock critical variables against reassignment.
#!/bin/bash
# Use default if ENV_VAR is unset or empty
ENV=${DEPLOY_ENV:-production}
PORT=${APP_PORT:-8080}
# Prevent accidental reassignment
readonly CONFIG_DIR="/etc/myapp"
echo "Env: $ENV, Port: $PORT, Config: $CONFIG_DIR"
Discussion