Variables and Environment

Learn about Bash variables, environment variables, shell expansion, arrays, and how to configure your shell environment effectively.

📖 4 min read📅 2026-02-10Core Concepts

Shell Variables

# Create a variable (NO spaces around =)
name="ShellRAG"
count=42
pi=3.14159
 
# Use a variable
echo $name
echo "Welcome to $name"
echo "Count is: ${count}"    # Braces for clarity
 
# WRONG: spaces around = will cause errors
# name = "value"   # ERROR: tries to run "name" as command

Quoting

name="World"
 
# Double quotes: Variables ARE expanded
echo "Hello, $name"        # "Hello, World"
 
# Single quotes: Variables are NOT expanded
echo 'Hello, $name'        # "Hello, $name"
 
# No quotes: Word splitting occurs
files="file1 file2 file3"
for f in $files; do echo $f; done   # Three iterations
for f in "$files"; do echo $f; done # One iteration
 
# Escape characters
echo "The cost is \$10"    # "The cost is $10"
echo "Line1\nLine2"        # Literal \n
echo -e "Line1\nLine2"     # Actual newline

Variable Operations

name="Hello World"
 
# String length
echo ${#name}               # 11
 
# Substring
echo ${name:0:5}            # "Hello"
echo ${name:6}              # "World"
 
# Default values
echo ${undefined:-"default"}    # "default" (use default if unset)
echo ${undefined:="default"}    # "default" (set and use default if unset)
 
# Substitution
filename="photo.jpg"
echo ${filename%.jpg}       # "photo" (remove suffix)
echo ${filename%.*}         # "photo" (remove extension)
echo ${filename##*.}        # "jpg" (extract extension)
echo ${filename/jpg/png}    # "photo.png" (replace first)
echo ${filename//o/0}       # "ph0t0.jpg" (replace all)
 
# Uppercase/Lowercase (Bash 4+)
text="hello world"
echo ${text^}               # "Hello world" (capitalize first)
echo ${text^^}              # "HELLO WORLD" (all upper)
TEXT="HELLO"
echo ${TEXT,}               # "hELLO" (lowercase first)
echo ${TEXT,,}              # "hello" (all lower)

Environment Variables

Environment variables are inherited by child processes:

# View all environment variables
env
printenv
 
# Common environment variables
echo $HOME          # Home directory
echo $USER          # Current username
echo $PATH          # Executable search path
echo $SHELL         # Current shell
echo $PWD           # Current directory
echo $HOSTNAME      # Machine hostname
echo $LANG          # Language/locale
echo $EDITOR        # Default text editor
echo $TERM          # Terminal type
 
# Set environment variable (for current session)
export MY_VAR="hello"
 
# Set for a single command
MY_VAR="test" ./script.sh
 
# Make permanent (add to ~/.bashrc)
echo 'export MY_VAR="hello"' >> ~/.bashrc

PATH Variable

# View PATH
echo $PATH
 
# Add to PATH
export PATH="$PATH:/new/directory"
 
# Add permanently (in ~/.bashrc)
export PATH="$HOME/bin:$PATH"
 
# Check if command is in PATH
which python
type git

Arrays

# Create array
fruits=("Apple" "Banana" "Cherry" "Date")
 
# Access elements (0-indexed)
echo ${fruits[0]}         # "Apple"
echo ${fruits[2]}         # "Cherry"
echo ${fruits[-1]}        # "Date" (last element)
 
# All elements
echo ${fruits[@]}         # All elements
echo ${fruits[*]}         # All elements (as single string)
 
# Array length
echo ${#fruits[@]}        # 4
 
# Array slice
echo ${fruits[@]:1:2}    # "Banana Cherry"
 
# Add element
fruits+=("Elderberry")
 
# Remove element
unset fruits[1]
 
# Iterate
for fruit in "${fruits[@]}"; do
    echo "I like $fruit"
done
 
# Associative arrays (Bash 4+)
declare -A capitals
capitals[France]="Paris"
capitals[Japan]="Tokyo"
capitals[Brazil]="Brasilia"
 
echo ${capitals[France]}       # "Paris"
echo ${!capitals[@]}           # All keys
echo ${capitals[@]}            # All values
 
for country in "${!capitals[@]}"; do
    echo "$country -> ${capitals[$country]}"
done

Special Variables

$0        # Script name
$1-$9     # Positional parameters (arguments)
${10}     # 10th argument (braces needed for 10+)
$#        # Number of arguments
$@        # All arguments (as separate words)
$*        # All arguments (as single string)
$$        # Current process ID
$!        # Last background process ID
$?        # Exit status of last command
$_        # Last argument of previous command

Using Arguments

#!/bin/bash
# save as greet.sh
 
echo "Script: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Arg count: $#"
 
# Usage: ./greet.sh Hello World
# Output:
# Script: ./greet.sh
# First arg: Hello
# Second arg: World
# All args: Hello World
# Arg count: 2

Arithmetic

# Using $(( ))
result=$((5 + 3))
echo $result          # 8
 
echo $((10 * 5))      # 50
echo $((20 / 3))      # 6 (integer division)
echo $((20 % 3))      # 2 (modulus)
echo $((2 ** 10))     # 1024 (exponent)
 
# Increment
count=0
((count++))
echo $count           # 1
 
# let command
let "x = 5 + 3"
echo $x               # 8
 
# For floating point, use bc
echo "scale=2; 20/3" | bc    # 6.66
echo "scale=4; 3.14 * 2" | bc  # 6.2800

Exercises

  1. Create a script that takes a filename as an argument and displays its extension
  2. Write a script using arrays to store server names and loop through them
  3. Create an associative array of error codes and descriptions
  4. Write a script that adds a directory to PATH only if it's not already there
  5. Use parameter expansion to rename all .txt files to .md in a directory

Next: Bash Scripting Basics — write your first scripts!