Variable Declaration and Assignment
Basic Variable Assignment
Variables store data that can be referenced and manipulated throughout your script:
Command:
VARIABLE_NAME="DevOps"
echo $VARIABLE_NAME
echo ${VARIABLE_NAME}Result:
DevOps
DevOpsNaming Conventions
# Valid variable names
my_var="value"
MY_VAR="value"
myVar="value"
my_var_123="value"
# Invalid (don't use)
123var="value" # Starts with number
my-var="value" # Contains hyphen
my var="value" # Contains spaceQuoting Variables
# Double quotes allow expansion
NAME="World"
echo "Hello $NAME" # Output: Hello World
# Single quotes prevent expansion
echo 'Hello $NAME' # Output: Hello $NAME
# No quotes (be careful)
echo Hello $NAME # Can split on whitespaceData Types
Bash is dynamically typed, but you should understand how different types behave:
Strings
GREETING="Hello, DevOps!"
MULTILINE="Line 1
Line 2
Line 3"Numbers
INTEGER=42
FLOAT=3.14
HEX=0xFF
OCTAL=0755Arrays
ARRAY=("item1" "item2" "item3")
echo ${ARRAY[0]} # item1
echo ${ARRAY[@]} # All items
echo ${#ARRAY[@]} # Array lengthParameter Expansion
Powerful syntax for manipulating variables:
Default Values
# Use default if unset
echo ${VAR:-"default"}
# Use default and set variable
echo ${VAR:="default"}
# Error if unset
echo ${VAR:?"Variable must be set"}String Manipulation
FILENAME="archive.tar.gz"
# Remove suffix
echo ${FILENAME%.tar.gz} # archive
# Remove prefix
echo ${FILENAME#archive.} # tar.gz
# Get length
echo ${#FILENAME} # 14
# Substring
echo ${FILENAME:0:7} # archiveSpecial Variables
Script and Command Context
$0 # Script filename
$1, $2 # Command-line arguments
$@ # All arguments as separate words
$* # All arguments as single string
$# # Number of arguments
$$ # Process ID
$? # Exit status of last command
$! # Process ID of last background jobExample
#!/bin/bash
echo "Script: $0"
echo "First argument: $1"
echo "Total arguments: $#"
echo "All arguments: $@"Environment Variables
Reading Environment Variables
echo $HOME # User home directory
echo $PATH # Command search path
echo $USER # Current user
echo $SHELL # Default shell
echo $PWD # Current working directorySetting Environment Variables
# Local variable (this script only)
MY_VAR="value"
# Export to child processes
export MY_VAR="value"
# Define in one line for a command
NODE_ENV=production npm startType Coercion and Arithmetic
Arithmetic Expansion
# Using (( ))
SUM=$((10 + 5))
echo $SUM # 15
# Using let
let RESULT=20*3
echo $RESULT # 60
# Using expr
RESULT=$(expr 15 - 8)
echo $RESULT # 7String to Number Conversion
NUM_STR="42"
NUM=$((NUM_STR + 8)) # Coerces to number
echo $NUM # 50Read-Only Variables
# Make variable read-only
readonly CONST="value"
CONST="new" # Error: CONST: is read only
# View read-only variables
readonly -p # List all read-only variablesVariable Scope
#!/bin/bash
GLOBAL="global"
my_function() {
LOCAL="local" # Only exists in function
echo $GLOBAL # Can access global
}
echo $LOCAL # Empty (LOCAL doesn't exist here)Best Practices
- Use meaningful, descriptive variable names
- Avoid single-letter variables except in loops
- Quote variables:
"$VAR"to handle spaces - Use uppercase for constants and exports
- Use lowercase for local variables
- Prefer
${VAR}syntax for clarity - Test for variable existence before use