Sagar.BlogArticle
All posts
All posts
Bash

Variables in Bash — Declare, Read, and Use

How to create and use variables in Bash scripts. Covers naming rules, assignment syntax, reading values, and common pitfalls.

January 4, 20267 min read
BashVariablesScripting

Variables are how your script remembers values. Unlike many languages, Bash variables are untyped — everything is a string. Understanding the assignment syntax and word-splitting rules saves hours of debugging.

Declaring Variables

# Assignment — NO spaces around =
name="Alice"         # ✅ correct
name = "Alice"       # ❌ wrong — Bash treats 'name' as a command
name="Alice Smith"   # ✅ quotes needed for spaces
count=42
pi=3.14159           # still a string internally

The most common Bash mistake

No spaces allowed around = in assignment. name = "Alice" tells Bash to run a command called name with arguments = and "Alice". You'll see command not found: name. Always write name="Alice".

Reading Variables

name="Alice"

echo $name            # prints: Alice
echo "$name"          # prints: Alice  (prefer this — safer with spaces)
echo "${name}"        # prints: Alice  (explicit boundary — necessary when concatenating)

# Concatenation
greeting="Hello, ${name}!"
echo "$greeting"      # Hello, Alice!

# Variable in middle of word — braces required
prefix="super"
echo "${prefix}man"   # superman
echo "$prefixman"     # empty — Bash looks for variable named 'prefixman'

Always quote your variables

Use "$var" instead of $var almost everywhere. Without quotes, if the variable contains spaces, Bash splits it into multiple words — causing bugs that are hard to trace.

file="my document.txt"
rm $file     # ❌ runs: rm my document.txt  (tries to delete TWO files)
rm "$file"   # ✅ runs: rm "my document.txt"  (one file)

Naming Rules

Variable naming conventions

StyleUsed for
lowercase_with_underscoresLocal script variables (recommended)
UPPERCASE_WITH_UNDERSCORESEnvironment variables / constants
Valid chars: letters, digits, _Cannot start with a digit

Default values

Bash has built-in syntax for providing defaults when a variable is unset or empty:

name=""

# ${var:-default}  →  use default if var is unset or empty
echo "${name:-World}"    # World   (name is empty)

name="Alice"
echo "${name:-World}"    # Alice   (name has a value)

# ${var:=default}  →  set AND use default if var is unset or empty
echo "${unset_var:=fallback}"   # fallback; also sets unset_var="fallback"

# ${var:?message}  →  print error and exit if var is unset or empty
: "${REQUIRED_VAR:?ERROR: REQUIRED_VAR must be set}"

Readonly Variables (Constants)

readonly MAX_RETRIES=3
readonly CONFIG_FILE="/etc/myapp/config.conf"

MAX_RETRIES=5  # ❌ bash: MAX_RETRIES: readonly variable

Unsetting Variables

name="Alice"
echo "$name"   # Alice
unset name
echo "$name"   # (empty)
Quick Check

What does `echo "${greeting:-Hello}"` print if `greeting` is unset?

Exercise

Write a script that:

  1. Stores your name in a variable name
  2. Stores the current year using command substitution: $(date +%Y)
  3. Prints: "Hi, I'm Alice and it's 2026." (using your variables)
  4. Also print the number of characters in your name using: ${#name}