Can we determine inside the very script whether it started as source
(.) or executable
(shebang or something alike)?
1 Answer
Test on $0
if you have a script:
#!/bin/bash
echo $0
and make it executable (chmod 755 test.sh
) and
do:
source test.sh
you get bash
(or something else depending on how you are logged in and what your shell is).
If you do
./test.sh
you get ./test.sh
, so assuming that the script knows how it is saved on the disc you should do:
if [ $(basename "$0") == "test.sh" ]
then
..... your code here for non-sourced
else
..... your code here for sourced
fi
-
1That depends heavily on the shell - and i think it might even depend on bash version. Definitiely zsh puts the file's - even a shell function's name - in $0 by default for sourced one.
ksh
does the same for sourced scripts. I thought i remembered bash doing it too - or it just does a separate $@? They're all different.– mikeservCommented Jun 29, 2015 at 21:12 -
you are of course right about the different shells. Therefore testing on the script name might be the safer bet.– AnthonCommented Jun 29, 2015 at 21:19
-
I think this might be a little hopeless. I didn't mean that in a snarky way, by the way. Though, looking back at it, i wish i had, that would have been a really good snark. What i meant was they all do it differently.
.
is just a shell's core functionality, really. A lot of shells, though, will put - at the very top of the script -. $0
in the value of$_
. So that's one way. Portably, though, i really believe it's hopeless.– mikeservCommented Jun 29, 2015 at 21:24 -
In the specific case where the shell is
bash
: The array variable $BASH_SOURCE will have one element at the top level of the script executed as a command, and more than one in a function or sourced file. Commented Jun 30, 2015 at 17:43
return
out of a dot script, but can't do so out of an executable script. That might not be very helpful.4
, instead of, say3
or5
?