G
GuideDevOps
Lesson 2 of 15

Variables & Data Types

Part of the Shell Scripting (Bash) tutorial series.

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
DevOps

Naming 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 space

Quoting 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 whitespace

Data 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=0755

Arrays

ARRAY=("item1" "item2" "item3")
echo ${ARRAY[0]}           # item1
echo ${ARRAY[@]}           # All items
echo ${#ARRAY[@]}          # Array length

Parameter 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}        # archive

Special 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 job

Example

#!/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 directory

Setting 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 start

Type 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                # 7

String to Number Conversion

NUM_STR="42"
NUM=$((NUM_STR + 8))        # Coerces to number
echo $NUM                   # 50

Read-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 variables

Variable 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