$0 holds the name (and path) used to invoke the script. Understanding and manipulating $0 lets you:
- Retrieve the script’s invoked name or full path
- Derive the absolute directory where the script resides
Table of Contents
- Getting the Invoked Script Name
- Extracting Only the Basename
- Dynamic Usage Messages with
SCRIPT_NAME - Graceful Exits via a
terminateHelper - Resolving the Script’s Directory (
WORK_DIR) - Quick Reference Table
- Links and References
1. Getting the Invoked Script Name
By default,$0 prints exactly how the script was called:
show-zero.sh and run:
2. Extracting Only the Basename
To obtain just the filename (dropping any leading directories), use shell parameter expansion:${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:
4. Graceful Exits via a terminate Helper
Centralize error reporting and custom exit codes:
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).dirnameextracts the parent directory.
On macOS,
readlink -f may not be available. Use brew install coreutils or alternative methods (realpath).6. Quick Reference Table
| Feature | Purpose | Example |
|---|---|---|
$0 | How the script was invoked | echo "$0" |
${0##*/} | Basename of the script | SCRIPT_NAME=${0##*/} |
| Dynamic heredoc usage messages | Embed SCRIPT_NAME in help text | cat <<USAGE… |
terminate() | Standardize error output and exit codes | terminate "message" 42 |
readlink -f + dirname | Compute absolute script directory (WORK_DIR) | WORK_DIR=$(dirname "$(readlink -f "$0")")" |
7. Links and References
These patterns make your Bash scripts more predictable, portable, and user-friendly—leveraging$0 effectively is a key skill for any shell scripter.