Skip to main content
In Bash scripting, the special parameter $0 holds the name (and path) used to invoke the script. Understanding and manipulating $0 lets you:
  1. Retrieve the script’s invoked name or full path
  2. Derive the absolute directory where the script resides
Below, we explore each technique with practical examples and patterns for robust, user-friendly scripts.

Table of Contents

  1. Getting the Invoked Script Name
  2. Extracting Only the Basename
  3. Dynamic Usage Messages with SCRIPT_NAME
  4. Graceful Exits via a terminate Helper
  5. Resolving the Script’s Directory (WORK_DIR)
  6. Quick Reference Table
  7. Links and References

1. Getting the Invoked Script Name

By default, $0 prints exactly how the script was called:
Save this as show-zero.sh and run:

2. Extracting Only the Basename

To obtain just the filename (dropping any leading directories), use shell parameter expansion:
Running:
Here ${0##*/} strips everything up to the last slash.

3. Dynamic Usage Messages with SCRIPT_NAME

Embedding the script’s basename in help text ensures accuracy, even if the file is renamed:
Example output:

4. Graceful Exits via a terminate Helper

Centralize error reporting and custom exit codes:
Example runs:
For more advanced flag parsing, consider using getopts to handle short and long options.

5. Resolving the Script’s Directory (WORK_DIR)

Hard-coding relative paths can break when you run scripts from different locations. Instead, compute the script’s own directory:
  • readlink -f "$0" returns the script’s canonical absolute path (following symlinks).
  • dirname extracts the parent directory.
Now you can reliably reference files relative to the script’s location:
On macOS, readlink -f may not be available. Use brew install coreutils or alternative methods (realpath).

6. Quick Reference Table


These patterns make your Bash scripts more predictable, portable, and user-friendly—leveraging $0 effectively is a key skill for any shell scripter.

Watch Video

Practice Lab