6

Can we determine inside the very script whether it started as source (.) or executable (shebang or something alike)?

7
  • You should be able to return out of a dot script, but can't do so out of an executable script. That might not be very helpful.
    – mikeserv
    Commented Jun 29, 2015 at 21:17
  • That's exactly why I wanna know! :))
    – DrBeco
    Commented Jun 29, 2015 at 21:48
  • Does SHLVL get incremented differently in the two cases? I am away from a Unix shell at the moment, or I'd test it myself.
    – Jeff Schaller
    Commented Jul 1, 2015 at 3:00
  • @JeffSchaller !! Maybe you just found the best answer. THEY DO! I never heard of this variable. Please do some tests to be sure thats ok, no side effects (works ok, all environments? Other shells? What other questions? Is it robust?), and write an answer here, and I'll change the accepted answer. This is very elegant.
    – DrBeco
    Commented Jul 4, 2015 at 3:25
  • Anyway, but how would you know if its supposed to be, lets say, 4, instead of, say 3 or 5?
    – DrBeco
    Commented Jul 4, 2015 at 3:26

1 Answer 1

2

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
4
  • 1
    That 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.
    – mikeserv
    Commented 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.
    – Anthon
    Commented 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.
    – mikeserv
    Commented 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .