36

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?

1

2 Answers 2

56

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 )"
To be safe, redirect the output of cd to /dev/null. cd outputs the directory being changed to when CDPATH is set.
-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"

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.