Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out name of script called ("sourced") by another script in bash? [duplicate]

Tags:

Possible Duplicate:
In the bash script how do I know the script file name?
How can you access the base filename of a file you are sourcing in Bash

When using source to call a bash script from another, I'm unable to find out from within that script what the name of the called script is.

file1.sh

#!/bin/bash
echo "from file1: $0"
source file2.sh

file2.sh

#!/bin/bash
echo "from file2: $0"

Running file1.sh

$ ./file1.sh
from file1: ./file1.sh  # expected
from file2: ./file1.sh  # was expecting ./file2.sh

Q: How can I retrieve file2.sh from file2.sh?

like image 954
Max Avatar asked Jan 18 '12 14:01

Max


People also ask

Which command is used to display the script name?

If we prefer not to print the path and only want the name of the script to show, we can use the basename command, which extracts the name from the path.

How do I get the script name inside a script in Unix?

If you invoke the script with path like /path/to/script.sh then $0 also will give the filename with path. In that case need to use $(basename $0) to get only script file name.


1 Answers

Change file2.sh to:

#!/bin/bash
echo "from file2: ${BASH_SOURCE[0]}"

Note that BASH_SOURCE is an array variable. See the Bash man pages for more information.

like image 124
dogbane Avatar answered Oct 06 '22 22:10

dogbane