Obtaining the current script's filename in a Bash script is straightforward. We can use the built-in variable $0 to retrieve the name of the current script. This variable contains the command used to launch the script, which is typically the script's path.
For example, suppose we have a script named script.sh. We can add the following code to print the script filename within the script:
bash#!/bin/bash echo "Script name: $0"
When you run this script, it will output something like:
shellScript name: ./script.sh
If you only want to obtain the filename without the path, you can use the basename command to extract the filename:
bash#!/bin/bash script_name=$(basename "$0") echo "Script name: $script_name"
This code uses basename "$0" to extract the filename from $0, even if $0 includes path information. When you run this script, the output will be:
shellScript name: script.sh
This approach is particularly useful for logging, generating output files with specific filenames, or when the script needs to reference its own filename.