Certainly! Here are examples demonstrating the use of $0 and $BASH_SOURCE in a Bash script.
Example of $0
Create a script named example0.sh:
#!/bin/bash
echo "The name of this script is: $0"
When you run this script from the command line:
./example0.sh
The output will be:
The name of this script is: ./example0.sh
Example of $BASH_SOURCE
Create two scripts: main.sh and helper.sh.
helper.sh:
#!/bin/bash
echo "This script is: ${BASH_SOURCE[0]}"
main.sh:
#!/bin/bash
source ./helper.sh
When you run main.sh from the command line:
./main.sh
The output will be:
This script is: ./helper.sh
In this example, $BASH_SOURCE[0] in helper.sh gives the name of the script that is currently being executed, which is helper.sh, even though it was called from main.sh.
