Getting the Script File Name in Bash

In Bash scripting, it’s often necessary to know the name of the script file itself. This can be useful for various purposes, such as logging, error handling, or displaying information about the script being executed. In this tutorial, we’ll explore how to obtain the script file name in a Bash script.

Using $0

The most straightforward way to get the script file name is by using the $0 variable. This variable always contains the path to the script as it was invoked. Here’s an example:

#!/bin/bash

script_name=$(basename "$0")
echo "You are running $script_name"

In this example, basename is used to extract the file name from the full path stored in $0.

Handling Symlinks

When dealing with symlinks, you might want to consider whether to resolve the link or use the original name. If you want to resolve the symlink, you can use the following approach:

#!/bin/bash

script_name=$(basename "$(readlink -f "$0")")
echo "You are running $script_name"

This will give you the actual script file name, even if it’s being executed through a symlink.

Using BASH_SOURCE

Another way to get the script file name is by using the BASH_SOURCE variable. This variable contains the path to the current source file. Here’s an example:

#!/bin/bash

script_name=$(basename "${BASH_SOURCE[0]}")
echo "You are running $script_name"

Note that BASH_SOURCE is an array, and we’re using the first element ([0]) to get the path to the current source file.

Best Practices

When working with script file names in Bash, it’s essential to follow best practices:

  • Always double-quote variable names to prevent word splitting or globbing.
  • Use basename to extract the file name from the full path.
  • Consider using readlink -f to resolve symlinks if needed.

By following these guidelines and using the methods described in this tutorial, you’ll be able to easily obtain the script file name in your Bash scripts.

Leave a Reply

Your email address will not be published. Required fields are marked *