DevOps Journey
Bash

Variables

Bash variables and data types

Variables

Variables store and manage data in Bash scripts.

Variable Basics

# Create a variable
VARIABLE_NAME="value"
count=5
path="/home/user"

# No spaces around equals sign
# Naming convention: UPPERCASE_WITH_UNDERSCORES for constants

# Access variables with $ prefix
echo $count
echo $VARIABLE_NAME

Variable Types

Strings

# String variable
name="Alice"
greeting="Hello, $name!" # variable expansion

# Single quotes prevent expansion
greeting='Hello, $name!' # outputs: Hello, $name!

# Concatenation
full_text="$greeting Nice to meet you."

# Multiline strings
multiline="This is
a multiline
string"

Numbers

# Bash treats all variables as strings by default
age=25
height=180

# Arithmetic operations with (( ))
x=$((10 + 5)) # x = 15
y=$((10 - 3)) # y = 7
z=$((4 * 6)) # z = 24
result=$((20 / 4)) # result = 5
remainder=$((17 % 5)) # remainder = 2

Arrays

# Indexed array
fruits=("apple" "banana" "orange")

# Access array element
echo ${fruits[0]} # apple
echo ${fruits[@]} # all elements
echo ${#fruits[@]} # array length

# Add to array
fruits+=("grape")

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

# Associative array (like dictionary)
declare -A person
person[name]="Bob"
person[age]=30
echo ${person[name]} # Bob

Variable Scoping

# Global variable (available everywhere)
global_var="I'm global"

# Local variable (only in function)
my_function() {
    local local_var="I'm local"
    echo $local_var # works here
}

echo $local_var # empty/not defined

Special Variables

# Command-line arguments
$0 # script name
$1 # first argument
$2 # second argument
$@ # all arguments as array
$* # all arguments as string
$# # number of arguments

# Process information
$$ # current process ID
$! # last background process ID
$? # exit status of last command

# Environment
$HOME # home directory
$PATH # executable paths
$USER # current username
$PWD # current directory

Variable Expansion

# Default value
${var:-default} # use default if var is empty
${var:=default} # set to default if empty

# Using value if set
${var:+alternate} # use alternate if var is set

# Error message if empty
${var:?error message}

# String manipulation
${var:0:5} # substring (first 5 chars)
${var:(-3)} # last 3 chars
${var/old/new} # replace first occurrence
${var//old/new} # replace all occurrences
${var#pattern} # remove prefix
${var%pattern} # remove suffix

Command Substitution

# Store command output in variable
current_date=$(date)
echo "Today is $current_date"

# Old syntax (still works)
current_date=`date`

# Nested command substitution
files=$(ls $(pwd))

Environment Variables

# View all environment variables
env
printenv

# Set environment variable
export MY_VAR="value"

# Access environment variable
echo $MY_VAR

# Unset variable
unset MY_VAR

Best Practices

  • Quote variables: "$var" to handle spaces
  • Use meaningful names
  • Use uppercase for constants
  • Validate input from command-line arguments
  • Use local variables in functions
  • Avoid single-letter variable names (except loops)
  • Clear/unset variables when done
  • Document what variables store

On this page