31

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?

Community
  • 1
  • 1
Max
  • 12,794
  • 30
  • 90
  • 142
  • @Matt - Especially that answer: http://stackoverflow.com/a/639500/45249 which suggests using `$BASH_SOURCE`. – mouviciel Jan 18 '12 at 14:34

2 Answers2

49

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.

dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 1
    if file2 is in a different directory then `$(basename ${BASH_SOURCE[0]})` seems to work better to get the filename only. To get the directory only use `"$( cd "$(dirname "$BASH_SOURCE")" ; pwd -P )"` – WiR3D Mar 01 '18 at 22:41
  • To be safe, redirect the output of `cd` to `/dev/null`. `cd` outputs the directory being changed to when `CDPATH` is set. – Noel Yap Jul 30 '21 at 05:57
-7

if you source a script then you are forcing the script to run in the current process/shell. This means variables in the script from file1.sh you ran are not lost. Since $0 was set to file1.sh it remains as is.

If you want to get the name of file2 then you can do something like this -

file1.sh

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

file2.sh

#!/bin/bash
echo "from file2: $0"
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
  • 2
    This invokes another shell instance and a handful of other things that are likely to be problematic and is very probably not what they were asking for, I know it's not what I was looking for. – Svartalf Oct 29 '20 at 01:29