What is `$0` commonly used for?

QuestionsQuestions8 SkillsProDec, 19 2025
0257

In shell scripting, $0 represents the name of the script currently being executed.

While $1, $2, etc., refer to the arguments you pass to a function or script, $0 is special because it refers to the "identity" of the process.

Here are the most common uses for $0:

1. Displaying Usage/Help Messages

This is its most frequent use. When a user provides the wrong arguments, it's a best practice to show them how to use the script. By using $0, the help message will always show the correct script name, even if the user renames the file.

if [ $# -lt 2 ]; then
    echo "Usage: $0 <number1> <number2>"
    exit 1
fi

If your script is named math_tool.sh, the output will be: Usage: ./math_tool.sh <number1> <number2>.

2. Logging

When writing logs to a file or the system console, $0 is used to identify which script generated the log entry.

echo "[$(date)]: $0 is starting the backup process..." >> backup.log

3. Finding the Script's Directory

Sometimes a script needs to find other files located in the same folder as itself. Developers use $0 with the dirname command to calculate the script's path.

SCRIPT_DIR=$(dirname "$0")
source "$SCRIPT_DIR/config.cfg"

4. Recursive Calls

Though rare in simple scripts, a script can use $0 to call itself again.


⚠️ A Crucial Note about Functions

In Bash, $0 does NOT change inside a function.

If you are inside a function and try to use $0, it will still return the name of the script, not the name of the function. To get the name of the current function, you should use the special variable ${FUNCNAME[0]}.

Example:

#!/bin/bash
my_function() {
    echo "Script name (\$0): $0"
    echo "Function name: ${FUNCNAME[0]}"
}

my_function

If you run this, $0 will be ./functions.sh, while ${FUNCNAME[0]} will be my_function.

0 Comments

no data
Be the first to share your comment!