Advanced Bash Scripting

Special Shell Variables

Overview

Shell scripting thrives on feedback—knowing whether each step succeeded, failed, or requires special handling. Special shell variables provide this introspection by exposing the shell environment, command-line arguments, process identifiers, and more. Leveraging these built-in indicators leads to more robust, maintainable scripts.

The image is a slide titled "Special Shell Variables," explaining that these variables allow access to information about the current shell environment and command-line arguments.

Understanding Exit Status in Bash

Every command you run returns an exit status:

  • 0 means success
  • Any nonzero value indicates failure

The special variable $? always holds the exit status of the last executed command:

$ ls /nonexistent
ls: cannot access '/nonexistent': No such file or directory
$ echo $?
2
$ echo "Listing current directory:"
$ ls
KodeKloud_introduction
$ echo $?
0

Note

Use echo $? immediately after a command to capture its exit status—subsequent commands will overwrite this value.

Exploring Common Special Shell Variables

Here’s a quick reference for the most widely used POSIX-compliant special parameters:

VariableDescriptionExample
$*All positional parameters as a single wordecho "Args: $*"
$#Number of positional parametersecho "Count: $#"
$0Name of the script or shellecho "Script: $0"
$!PID of the last background commandsleep 30 & then echo $!
$-Current shell options (flags) as a stringecho "Options: $-"

Each of these variables updates dynamically based on the context in which your script runs.

Warning

Expanding $* without quotes can lead to word splitting and unintended globbing. Use quotes or consider $@ when preserving argument boundaries is critical.

Practical Use Cases

  1. Argument Validation
    if [ $# -lt 2 ]; then
      echo "Usage: $0 <source> <destination>"
      exit 1
    fi
    
  2. Logging Script Name
    echo "[$(date)] Starting backup script: $0"
    
  3. Background Job Monitoring
    long_running_task &
    bg_pid=$!
    wait $bg_pid
    echo "Job $bg_pid finished with status $?"
    

Watch Video

Watch video content

Previous
Subshells