Skip to main content

Chapter 6.2 - Variables and Parameters

Learning Objectives​

By the end of this chapter, you will be able to:

  • Use advanced variables
  • Work with script parameters
  • Understand special variables
  • Use arrays
  • Manage environment variables

Advanced Variables​

Variable Substitution​

#!/bin/bash
VAR="hello"

# Default value
echo ${VAR:-"default"} # hello (if VAR exists)
echo ${UNDEF:-"default"} # default (if UNDEF does not exist)

# Assign if undefined
echo ${VAR:="default"} # hello (VAR already exists)
echo ${UNDEF:="default"} # default (and assigns UNDEF)

# Error if undefined
echo ${VAR:?"VAR is not defined"} # OK
echo ${UNDEF:?"UNDEF is not defined"} # Error

# Remove prefix/suffix
FILE="file.txt"
echo ${FILE%.txt} # file (removes .txt)
echo ${FILE#file} # .txt (removes file)

String Length​

#!/bin/bash
TEXT="Linux"
echo ${#TEXT} # 5 (length)

Substring Extraction​

#!/bin/bash
TEXT="Hello Linux World"
echo ${TEXT:6} # Linux World (from position 6)
echo ${TEXT:6:5} # Linux (position 6, length 5)

Script Parameters​

Positional Arguments​

#!/bin/bash
# $0: Script name
# $1, $2, $3...: Arguments
# $#: Number of arguments
# $@: All arguments (separated)
# $*: All arguments (as a string)

echo "Script: $0"
echo "First: $1"
echo "Second: $2"
echo "Count: $#"
echo "All (@): $@"
echo "All (*): $*"

Example:

./script.sh arg1 arg2 arg3
# $0 = ./script.sh
# $1 = arg1
# $2 = arg2
# $3 = arg3
# $# = 3

Argument Shifting​

#!/bin/bash
# shift: Shifts arguments
echo "1: $1"
shift
echo "2: $1" # Former $2
shift
echo "3: $1" # Former $3

Iterating Over Arguments​

#!/bin/bash
# Method 1: $@
for arg in "$@"; do
echo "Argument: $arg"
done

# Method 2: $*
for arg in $*; do
echo "Argument: $arg"
done

# Method 3: while with shift
while [ $# -gt 0 ]; do
echo "Argument: $1"
shift
done

Arrays​

Declaration​

#!/bin/bash
# Declaration
FRUITS=("apple" "banana" "orange")

# Or
FRUITS[0]="apple"
FRUITS[1]="banana"
FRUITS[2]="orange"

Access​

#!/bin/bash
FRUITS=("apple" "banana" "orange")

# Specific element
echo ${FRUITS[0]} # apple
echo ${FRUITS[1]} # banana

# All elements
echo ${FRUITS[@]} # apple banana orange
echo ${FRUITS[*]} # apple banana orange

# Length
echo ${#FRUITS[@]} # 3

# Indices
echo ${!FRUITS[@]} # 0 1 2

Iterating Over an Array​

#!/bin/bash
FRUITS=("apple" "banana" "orange")

# By value
for fruit in "${FRUITS[@]}"; do
echo "Fruit: $fruit"
done

# By index
for i in "${!FRUITS[@]}"; do
echo "$i: ${FRUITS[$i]}"
done

Environment Variables​

Define​

#!/bin/bash
# Local variable (script only)
LOCAL_VAR="local"

# Environment variable (exported)
export ENV_VAR="environment"

# Or
ENV_VAR="environment"
export ENV_VAR

Common System Variables​

#!/bin/bash
echo "HOME: $HOME"
echo "USER: $USER"
echo "PATH: $PATH"
echo "SHELL: $SHELL"
echo "PWD: $PWD"
echo "UID: $UID"
echo "EUID: $EUID"

Modify PATH​

#!/bin/bash
# Add to PATH
export PATH="$PATH:/path/to/bin"

# Temporary (script only)
PATH="$PATH:/path/to/bin"

Special Variables​

Return Code​

#!/bin/bash
# $?: Return code of the last command
ls /tmp
echo "Code: $?" # 0 if success

# Test
if [ $? -eq 0 ]; then
echo "Success"
else
echo "Failure"
fi

PID and Processes​

#!/bin/bash
echo "Current PID: $$"
echo "Parent PID: $PPID"
echo "Last background PID: $!"

Shell Options​

#!/bin/bash
# $-: Active options
echo "Options: $-"

Complete Example​

#!/bin/bash
# Script with parameters and arrays

# Help function
show_help() {
echo "Usage: $0 [OPTIONS] FILES..."
echo "Options:"
echo " -h Help"
echo " -v Verbose mode"
echo " -o Output file"
}

# Variables
VERBOSE=false
OUTPUT=""
FILES=()

# Parse arguments
while [ $# -gt 0 ]; do
case $1 in
-h)
show_help
exit 0
;;
-v)
VERBOSE=true
;;
-o)
shift
OUTPUT="$1"
;;
*)
FILES+=("$1")
;;
esac
shift
done

# Processing
if [ ${#FILES[@]} -eq 0 ]; then
echo "Error: No files specified"
exit 1
fi

[ "$VERBOSE" = true ] && echo "Processing ${#FILES[@]} file(s)"

for file in "${FILES[@]}"; do
[ "$VERBOSE" = true ] && echo "Processing: $file"
# Processing...
done

Summary​

In this chapter, you learned:

Substitution: \${VAR:-default}, \${VAR%pattern}, etc.
Parameters: $0, $1-$n, $#, $@, $*
Arrays: Declaration, access, iteration
Environment: export, system variables
Specials: $?, $$, $PPID, $-
Parsing: while + case for arguments


Next Steps​

Chapter 6.3: Control Structures
Chapter 6.4: Functions and Cron


Chapter created on: December 2024