How to detect if a script is being sourced
Asked Answered
G

26

345

I have a script where I do not want it to call exit if it's being sourced.

I thought of checking if $0 == bash but this has problems if the script is sourced from another script, or if the user sources it from a different shell like ksh.

Is there a reliable way of detecting if a script is being sourced?

Guarantor answered 21/4, 2010 at 13:28 Comment(2)
I had a similar issue a while back and solved it by avoiding 'exit' in all cases; "kill -INT $$" terminates the script safely in either case.Bittersweet
Did you notice this answer? It is given 5 years later from the accepted, but it has "batteries included".Velamen
D
89

This seems to be portable between Bash and Korn:

[[ $_ != $0 ]] && echo "Script is being sourced" || echo "Script is a subshell"

A line similar to this or an assignment like pathname="$_" (with a later test and action) must be on the first line of the script or on the line after the shebang (which, if used, should be for ksh in order for it to work under the most circumstances).

Doubles answered 21/4, 2010 at 22:49 Comment(12)
Unfortunately it's not guaranteed to work. If the user has set BASH_ENV, $_ at the top of the script will be the last command run from BASH_ENV.Yaekoyael
This will also not work if you use bash to execute the script, e.g. $ bash script.sh then the $_ would be /bin/bash instead of ./script.sh, which is the case you expect, when the script is invoked in this way: $ ./script.sh In any case detecting with $_ is a problem.Uncommonly
Additional tests could be included to check for those invocation methods.Doubles
Unfortunely, that's wrong! see my answerExtraction
@UpAndAdam: True, captured or used immediately. I have described the latter in my answer.Doubles
Might be good to emphasize that point given the importance of portability in this questionErnestineernesto
To summarize: While this approach typically works, it is not robust; it fails in the following 2 scenarios: (a) bash script (invocation via shell executable, which this solution misreports as sourced), and (b) (far less likely) echo bash; . script (if $_ happens to match the shell sourcing the script, this solution misreports it as a subshell). Only shell-specific special variables (e.g, $BASH_SOURCE) allow robust solutions (it follows that there is no robust POSIX-compliant solution). It is possible, albeit cumbersome, to craft a robust cross-shell test.Extern
@JPope2014: The answer is in the OP's question. "Initially I though checking if $0 == bash but this has problems if the script is sourced from another script, or if the user sources it from ksh."Doubles
fails when echo "anything" is used before thisCohe
@meso_2600: I say "must be on the first line of the script" in my answer.Doubles
This doesn't work. I tested on Ubuntu 14.04 with BASH.Oza
Does not work for me. Should not be the accepted answer.Unfit
E
292

Robust solutions for bash, ksh, zsh, including a cross-shell one, plus a reasonably robust POSIX-compliant solution:

  • Version numbers given are the ones on which functionality was verified - likely, these solutions work on much earlier versions, too - feedback welcome.

  • Using POSIX features only (such as in dash, which acts as /bin/sh on Ubuntu), there is no robust way to determine if a script is being sourced - see below for the best approximation.

Important:

  • The solutions determine whether the script is being sourced by its caller, which may be a shell itself or another script (which may or may not be sourced itself):

    • Also detecting the latter case adds complexity; if you do not need to detect the case when your script is being sourced by another script, you can use the following, relatively simple POSIX-compliant solution:

       # Helper function
       is_sourced() {
         if [ -n "$ZSH_VERSION" ]; then 
             case $ZSH_EVAL_CONTEXT in *:file:*) return 0;; esac
         else  # Add additional POSIX-compatible shell names here, if needed.
             case ${0##*/} in dash|-dash|bash|-bash|ksh|-ksh|sh|-sh) return 0;; esac
         fi
         return 1  # NOT sourced.
       }
      
       # Sample call.
       is_sourced && sourced=1 || sourced=0
      
  • All solutions below must run in the top-level scope of your script, not inside functions.

One-liners follow - explanation below; the cross-shell version is complex, but it should work robustly:

  • bash (verified on 3.57, 4.4.19, and 5.1.16)
(return 0 2>/dev/null) && sourced=1 || sourced=0
  • ksh (verified on 93u+)
[[ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ]] && sourced=1 || sourced=0
  • zsh (verified on 5.0.5)
[[ $ZSH_EVAL_CONTEXT =~ :file$ ]] && sourced=1 || sourced=0
  • cross-shell (bash, ksh, zsh)
(
  [[ -n $ZSH_VERSION && $ZSH_EVAL_CONTEXT =~ :file$ ]] || 
  [[ -n $KSH_VERSION && "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ]] || 
  [[ -n $BASH_VERSION ]] && (return 0 2>/dev/null)
) && sourced=1 || sourced=0
  • POSIX-compliant; not a one-liner (single pipeline) for technical reasons and not fully robust (see bottom):
sourced=0
if [ -n "$ZSH_VERSION" ]; then 
  case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
  [ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
  (return 0 2>/dev/null) && sourced=1 
else # All other shells: examine $0 for known shell binary filenames.
     # Detects `sh` and `dash`; add additional shell filenames as needed.
  case ${0##*/} in sh|-sh|dash|-dash) sourced=1;; esac
fi

Explanations


bash

(return 0 2>/dev/null) && sourced=1 || sourced=0

Note: The technique was adapted from user5754163's answer, as it turned out to be more robust than the original solution, [[ $0 != "$BASH_SOURCE" ]] && sourced=1 || sourced=0[1]

  • Bash allows return statements only from functions and, in a script's top-level scope, only if the script is sourced.

    • If return is used in the top-level scope of a non-sourced script, an error message is emitted, and the exit code is set to 1.
  • (return 0 2>/dev/null) executes return in a subshell and suppresses the error message; afterwards the exit code indicates whether the script was sourced (0) or not (1), which is used with the && and || operators to set the sourced variable accordingly.

    • Use of a subshell is necessary, because executing return in the top-level scope of a sourced script would exit the script.
    • Tip of the hat to @Haozhun, who made the command more robust by explicitly using 0 as the return operand; he notes: per bash help of return [N]: "If N is omitted, the return status is that of the last command." As a result, the earlier version [which used just return, without an operand] produces incorrect result if the last command on the user's shell has a non-zero return value.

ksh

[[ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ]] && sourced=1 || sourced=0

Special variable ${.sh.file} is somewhat analogous to $BASH_SOURCE; note that ${.sh.file} causes a syntax error in bash, zsh, and dash, so be sure to execute it conditionally in multi-shell scripts.

Unlike in bash, $0 and ${.sh.file} are NOT guaranteed to be the same - at different times either may be a relative path or mere file name, while the other may be a full one; therefore, both $0 and ${.sh.file} must be resolved to full paths before comparing. If the full paths differ, sourcing is implied.


zsh

[[ $ZSH_EVAL_CONTEXT =~ :file$) ]] && sourced=1 || sourced=0

$ZSH_EVAL_CONTEXT contains information about the evaluation context: substring file, separated with :, is only present if the script is being sourced.

In a sourced script's top-level scope, $ZSH_EVAL_CONTEXT ends with :file, and that's what this test is limited to. Inside a function, :shfunc is appended to :file; inside a command substitution, :cmdsubst, is appended.


Using POSIX features only

If you're willing to make certain assumptions, you can make a reasonable, but not fool-proof guess as to whether your script is being sourced, based on knowing the binary filenames of the shells that may be executing your script.
Notably, this means that this approach doesn't detect the case when your script is being sourced by another script.

The section "How to handle sourced invocations" in this answer discusses the edge cases that cannot be handled with POSIX features only in detail.

Examining the binary filename relies on the standard behavior of $0, which zsh, for instance, does not exhibit.

Thus, the safest approach is to combine the robust, shell-specific methods above - which do not rely on $0 - with a $0-based fallback solution for all remaining shells.

In short: The following solution:

  • in the shells that are covered with shell-specific tests: works robustly.

  • in all other shells: works only as expected when the script is being sourced directly from such a shell, as opposed to from another script.

Tip of the hat to Stéphane Desneux and his answer for the inspiration (transforming my cross-shell statement expression into a sh-compatible if statement and adding a handler for other shells).

sourced=0
if [ -n "$ZSH_VERSION" ]; then 
  case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
  [ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
  (return 0 2>/dev/null) && sourced=1 
else # All other shells: examine $0 for known shell binary filenames.
  # Detects `sh` and `dash`; add additional shell filenames as needed.
  case ${0##*/} in sh|-sh|dash|-dash) sourced=1;; esac
fi

Note that, for robustness, each shell binary filename (e.g. sh) is represented twice - once as-is and a second time, prefixed with -. This is to account for environments, such as macOS, where interactive shells are launched as login shells with a custom $0 value that is the (path-less) shell filename prefixed with -.Thanks, t7e. (While sh and dash are perhaps unlikely to be used as interactive shells, others that you may need to add to the list may.)


[1] user1902689 discovered that [[ $0 != "$BASH_SOURCE" ]] yields a false positive when you execute a script located in the $PATH by passing its mere filename to the bash binary; e.g., bash my-script, because $0 is then just my-script, whereas $BASH_SOURCE is the full path. While you normally wouldn't use this technique to invoke scripts in the $PATH - you'd just invoke them directly (my-script) - it is helpful when combined with -x for debugging.

Extern answered 27/2, 2015 at 23:37 Comment(16)
${0##*/} and $() aren't portable to at least one older Bourne shell (that I still have to use, even if it is a shame that it is necessary): echo ${0##*/} yields bad substitution, and echo $(dirname $0) gives syntax error: '(' unexpected. echo $0 gives -sh.Sexism
This fails your test and I did not source anything: echo $( echo $( echo 321 | echo $( return 0 2>/dev/null ) ) ); echo $?Pregnable
There is a case where bash specific code fails under bash 5Coimbra
@Thatoneguyfromthemovie, it's unclear how your example command relates to the answer, which is about scripts. Note that in your command you'll only ever see echo's own exit code, which is 0 - it doesn't matter what exit code the command inside the command substitution ($(...)) sets; try echo $(nosuchcommand); echo $?Extern
The Bash version doesn't play nice with set -euo pipefail.Haden
@mhvelplund, I don't see a problem if I execute that statement first - can you describe the problem in detail? On a general note, the unspoken assumption - not just for this answer, but probably most Unix shell-scripting answer - is that options are at their default.Extern
Please update zsh with case $ZSH_EVAL_CONTEXT in *:file*) sourced=1;; esac because the output can be toplevel:file:shfunc and not just toplevel:fileSunlit
@t7e, I've updated the answer to make it clearer that all snippets require running in the script's top-level scope, not inside functions. Making them all work inside functions as well, across all shells, adds too much complexity.Extern
Ok, I'll add my answer then, because I struggled to understand why that function did not work for me.Sunlit
The bash method also works for zsh for me.Habitue
ubuntu 22 adds dashes, so I had to do something like that case "$(printf '%s' "${0##*/}" | sed 's/-//')" in sh|dash|bash) echo "Bash is sourced";; esacSunlit
Thanks, @Sunlit - please see my update at the bottom. I wasn't aware of Ubuntu, but it can happen on macOS too, for interactive shells. For simplicity and performance and since the list is likely to be small, I've simply doubled the case branch entries ('sh|-sh|...) rather than rely on a command substitution with sedExtern
I guess, you need to change return 1 # NOT sourced. to exit 1 # NOT sourced. Because if it is sourced, use return 0 but if it is not, exit 1. return 1 may not stop the sequence while exit 1 will be safe because the script was run in a new shell.Sunlit
@t7e, the is_sourced() function isn't designed to exit, it is designed to return to the caller and communicate the sourced status via its exit code (0 for sourced, 1 for non-sourced); The sample statement is_sourced && sourced=1 || sourced=0 acts on that code.Extern
In the current code, you have a comment return 1 # NOT sourced, but that case where is_sourced=1 is the case where it is sourced. Remove the word NOT in the comment.Reiterant
@HumpbackWhale194, 1 as an exit code correctly indicates the non-sourced case, signaled via a nonzero exit code. That is, the exit-code logic is the inverse of the logic expressed in the quasi-Boolean sourced variable: In other words: exit code 0` means success - which triggers the && operand - and any nonzero exit code means failure, which triggers the || operand in the is_sourced && sourced=1 || sourced=0 statement.Extern
C
228

If your Bash version knows about the BASH_SOURCE array variable, try something like:

# man bash | less -p BASH_SOURCE
#[[ ${BASH_VERSINFO[0]} -le 2 ]] && echo 'No BASH_SOURCE array variable' && exit 1

[[ "${BASH_SOURCE[0]}" != "${0}" ]] && echo "script ${BASH_SOURCE[0]} is being sourced ..."
Composed answered 21/4, 2010 at 15:30 Comment(9)
That's maybe the cleanest way as $BASH_SOURCE is intended for that purpose exactly.Postmark
Note that this won't work under ksh which is a condition that the OP specified.Doubles
Is there a reason to use ${BASH_SOURCE[0]} instead of just $BASH_SOURCE? And ${0} vs $0?Incapacious
BASH_SOURCE is an array variable (see manual) that holds a stack trace of sources, where ${BASH_SOURCE[0]} is the latest one. The braces are used here to tell the bash what is part of the variable name. They are not necessary for $0 in this case, but they do not hurt either. ;)Outfight
@Konrad, and if you expand $array, you get ${array[0]} by default. So, again, is there a reason[...]?Sowder
Thanks for the "less -p <pattern>" usage -- very useful option which I had missed.Bittersweet
yeahhh, $_ vs $0 doesn't work, ${BASH_SOURCE[0]} vs $0 works!Epiglottis
@CharlesDuffy the only reason I can think of is that $array == ${array[0]} is a weird and unexpected bit of idiosyncratic syntax. A reader unfamiliar with that fact about bash variable expansion could be confused by the less-explicit syntax.Dissolution
Not sure if the double "" quotes within the double [[ ]] brackets are necessary.Bisk
D
89

This seems to be portable between Bash and Korn:

[[ $_ != $0 ]] && echo "Script is being sourced" || echo "Script is a subshell"

A line similar to this or an assignment like pathname="$_" (with a later test and action) must be on the first line of the script or on the line after the shebang (which, if used, should be for ksh in order for it to work under the most circumstances).

Doubles answered 21/4, 2010 at 22:49 Comment(12)
Unfortunately it's not guaranteed to work. If the user has set BASH_ENV, $_ at the top of the script will be the last command run from BASH_ENV.Yaekoyael
This will also not work if you use bash to execute the script, e.g. $ bash script.sh then the $_ would be /bin/bash instead of ./script.sh, which is the case you expect, when the script is invoked in this way: $ ./script.sh In any case detecting with $_ is a problem.Uncommonly
Additional tests could be included to check for those invocation methods.Doubles
Unfortunely, that's wrong! see my answerExtraction
@UpAndAdam: True, captured or used immediately. I have described the latter in my answer.Doubles
Might be good to emphasize that point given the importance of portability in this questionErnestineernesto
To summarize: While this approach typically works, it is not robust; it fails in the following 2 scenarios: (a) bash script (invocation via shell executable, which this solution misreports as sourced), and (b) (far less likely) echo bash; . script (if $_ happens to match the shell sourcing the script, this solution misreports it as a subshell). Only shell-specific special variables (e.g, $BASH_SOURCE) allow robust solutions (it follows that there is no robust POSIX-compliant solution). It is possible, albeit cumbersome, to craft a robust cross-shell test.Extern
@JPope2014: The answer is in the OP's question. "Initially I though checking if $0 == bash but this has problems if the script is sourced from another script, or if the user sources it from ksh."Doubles
fails when echo "anything" is used before thisCohe
@meso_2600: I say "must be on the first line of the script" in my answer.Doubles
This doesn't work. I tested on Ubuntu 14.04 with BASH.Oza
Does not work for me. Should not be the accepted answer.Unfit
E
83

After reading @DennisWilliamson's answer, there are some issues, see below:

As this question stand for and , there is another part in this answer concerning ... see below.

Simple way

[ "$0" = "$BASH_SOURCE" ]

Let's try (on the fly because that bash could ;-):

source <(echo $'#!/bin/bash
           [ "$0" = "$BASH_SOURCE" ] && v=own || v=sourced;
           echo "process $$ is $v ($0, $BASH_SOURCE)" ')
process 29301 is sourced (bash, /dev/fd/63)

bash <(echo $'#!/bin/bash
           [ "$0" = "$BASH_SOURCE" ] && v=own || v=sourced;
           echo "process $$ is $v ($0, $BASH_SOURCE)" ')
process 16229 is own (/dev/fd/63, /dev/fd/63)

I use source instead off . for readability (as . is an alias to source):

. <(echo $'#!/bin/bash
           [ "$0" = "$BASH_SOURCE" ] && v=own || v=sourced;
           echo "process $$ is $v ($0, $BASH_SOURCE)" ')
process 29301 is sourced (bash, /dev/fd/63)

Note that process number don't change while process stay sourced:

echo $$
29301

Why not to use $_ == $0 comparison

For ensuring many case, I begin to write a true script:

#!/bin/bash

# As $_ could be used only once, uncomment one of two following lines

#printf '_="%s", 0="%s" and BASH_SOURCE="%s"\n' "$_" "$0" "$BASH_SOURCE"
[[ "$_" != "$0" ]] && DW_PURPOSE=sourced || DW_PURPOSE=subshell

[ "$0" = "$BASH_SOURCE" ] && BASH_KIND_ENV=own || BASH_KIND_ENV=sourced;
echo "proc: $$[ppid:$PPID] is $BASH_KIND_ENV (DW purpose: $DW_PURPOSE)"

Copy this to a file called testscript:

cat >testscript   
chmod +x testscript

Now we could test:

./testscript 
proc: 25758[ppid:24890] is own (DW purpose: subshell)

That's ok.

. ./testscript 
proc: 24890[ppid:24885] is sourced (DW purpose: sourced)

source ./testscript 
proc: 24890[ppid:24885] is sourced (DW purpose: sourced)

That's ok.

But,for testing a script before adding -x flag:

bash ./testscript 
proc: 25776[ppid:24890] is own (DW purpose: sourced)

Or to use pre-defined variables:

env PATH=/tmp/bintemp:$PATH ./testscript 
proc: 25948[ppid:24890] is own (DW purpose: sourced)

env SOMETHING=PREDEFINED ./testscript 
proc: 25972[ppid:24890] is own (DW purpose: sourced)

This won't work anymore.

Moving comment from 5th line to 6th would give more readable answer:

./testscript 
_="./testscript", 0="./testscript" and BASH_SOURCE="./testscript"
proc: 26256[ppid:24890] is own

. testscript 
_="_filedir", 0="bash" and BASH_SOURCE="testscript"
proc: 24890[ppid:24885] is sourced

source testscript 
_="_filedir", 0="bash" and BASH_SOURCE="testscript"
proc: 24890[ppid:24885] is sourced

bash testscript 
_="/bin/bash", 0="testscript" and BASH_SOURCE="testscript"
proc: 26317[ppid:24890] is own

env FILE=/dev/null ./testscript 
_="/usr/bin/env", 0="./testscript" and BASH_SOURCE="./testscript"
proc: 26336[ppid:24890] is own

Harder: now...

As I don't use a lot, after some read on the man page, there is my tries:

#!/bin/ksh

set >/tmp/ksh-$$.log

Copy this in a testfile.ksh:

cat >testfile.ksh
chmod +x testfile.ksh

Than run it two time:

./testfile.ksh
. ./testfile.ksh

ls -l /tmp/ksh-*.log
-rw-r--r-- 1 user user   2183 avr 11 13:48 /tmp/ksh-9725.log
-rw-r--r-- 1 user user   2140 avr 11 13:48 /tmp/ksh-9781.log

echo $$
9725

and see:

diff /tmp/ksh-{9725,9781}.log | grep ^\> # OWN SUBSHELL:
> HISTCMD=0
> PPID=9725
> RANDOM=1626
> SECONDS=0.001
>   lineno=0
> SHLVL=3

diff /tmp/ksh-{9725,9781}.log | grep ^\< # SOURCED:
< COLUMNS=152
< HISTCMD=117
< LINES=47
< PPID=9163
< PS1='$ '
< RANDOM=29667
< SECONDS=23.652
<   level=1
<   lineno=1
< SHLVL=2

There is some variable herited in a sourced run, but nothing really related...

You could even check that $SECONDS is close to 0.000, but that's ensure only manualy sourced cases...

You even could try to check for what's parent is:

Place this into your testfile.ksh:

ps $PPID

Than:

./testfile.ksh
  PID TTY      STAT   TIME COMMAND
32320 pts/4    Ss     0:00 -ksh

. ./testfile.ksh
  PID TTY      STAT   TIME COMMAND
32319 ?        S      0:00 sshd: user@pts/4

or ps ho cmd $PPID, but this work only for one level of subsessions...

Sorry, I couldn't find a reliable way of doing that, under .

Extraction answered 11/4, 2014 at 9:44 Comment(3)
[ "$0" = "$BASH_SOURCE" ] || [ -z "$BASH_SOURCE" ] for scripts read in via pipe (cat script | bash).Mccarver
Note that . isn't an alias for source, it's actually the other way around. source somescript.sh is a Bash-ism and isn't portable, . somescript.sh is POSIX and portable IIRC.Shakedown
This breaks your theory. env -i echo $( source hi ); contents of hi: # source me [ "$_" == "0" ] && { echo "I succeed but does that really say I am sourced?" } || { echo "I failed but does that mean I am not sourced?" }Pregnable
L
34

The BASH_SOURCE[] answer (bash-3.0 and later) seems simplest, though BASH_SOURCE[] is not documented to work outside a function body (it currently happens to work, in disagreement with the man page).

The most robust way, as suggested by Wirawan Purwanto, is to check FUNCNAME[1] within a function:

function mycheck() { declare -p FUNCNAME; }
mycheck

Then:

$ bash sourcetest.sh
declare -a FUNCNAME='([0]="mycheck" [1]="main")'
$ . sourcetest.sh
declare -a FUNCNAME='([0]="mycheck" [1]="source")'

This is the equivalent to checking the output of caller, the values main and source distinguish the caller's context. Using FUNCNAME[] saves you capturing and parsing caller output. You need to know or calculate your local call depth to be correct though. Cases like a script being sourced from within another function or script will cause the array (stack) to be deeper. (FUNCNAME is a special bash array variable, it should have contiguous indexes corresponding to the call stack, as long as it is never unset.)

function issourced() {
    [[ ${FUNCNAME[@]: -1} == "source" ]]
}

(In bash-4.2 and later you can use the simpler form ${FUNCNAME[-1]} instead for the last item in the array. Improved and simplified thanks to Dennis Williamson's comment below.)

However, your problem as stated is "I have a script where I do not want it to call 'exit' if it's being sourced". The common bash idiom for this situation is:

return 2>/dev/null || exit

If the script is being sourced then return will terminate the sourced script and return to the caller.

If the script is being executed, then return will return an error (redirected), and exit will terminate the script as normal. Both return and exit can take an exit code, if required.

Sadly, this doesn't work in ksh (at least not in the AT&T derived version I have here), it treats return as equivalent to exit if invoked outside a function or dot-sourced script.

Updated: What you can do in contemporary versions of ksh is to check the special variable .sh.level which is set to the function call depth. For an invoked script this will initially be unset, for a dot-sourced script it will be set to 1.

function issourced {
    [[ ${.sh.level} -eq 2 ]]
}

issourced && echo this script is sourced

This is not quite as robust as the bash version, you must invoke issourced() in the file you are testing from at the top level or at a known function depth.

(You may also be interested in this code on github which uses a ksh discipline function and some debug trap trickery to emulate the bash FUNCNAME array.)

The canonical answer here: http://mywiki.wooledge.org/BashFAQ/109 also offers $- as another indicator (though imperfect) of the shell state.


Notes:

  • it is possible to create bash functions named "main" and "source" (overriding the builtin), these names may appear in FUNCNAME[] but as long as only the last item in that array is tested there is no ambiguity.
  • I don't have a good answer for pdksh. The closest thing I can find applies only to pdksh, where each sourcing of a script opens a new file descriptor (starting with 10 for the original script). Almost certainly not something you want to rely on...
Luge answered 5/2, 2013 at 11:42 Comment(5)
How about ${FUNCNAME[(( ${#FUNCNAME[@]} - 1 ))]} to get the last (bottom) item in the stack? Then testing against "main" (negate for OP) was the most reliable for me.Goosefish
If I have a PROMPT_COMMAND set, that shows up as the last index of the FUNCNAME array if I run source sourcetest.sh. Inverting the check (looking for main as the last index) seems more robust: is_main() { [[ ${FUNCNAME[@]: -1} == "main" ]]; }.Tentative
The man-page states, that FUNCNAME is only available in functions. According to my tests with declare -p FUNCNAME, bash behaves differently. v4.3 gives an error outside functions, while v4.4 gives declare -a FUNCNAME. Both(!) return main for ${FUNCNAME[0]} in the main script (if it is executed) while $FUNCNAME gives nothing. And: There are so many scripts out there "ab"using $BASH_SOURCE outside functions, that I doubt this can or will be changed.Epimenides
If all you want to do is return v. exit, use kill -1 $$ .. there are other reasons why one would want to know if they are sourced or not... I.E. subshell make environments for ({massively ,}parallel builds. In that case, just source a new version or the environment that you ran the jobs manually. /shrug it works... there is always a work-around, it just sucks when you're the guy always hitting the corner-case. LOLPregnable
After about a year of using and recommending the ${FUNCNAME[-1]} technique, I have completely rescinded. It does not work properly with nested scripts! You'd have to manually update the index according to the level of nesting, which isn't foreseeable nor practical. The technique using if [ "${BASH_SOURCE[0]}" = "$0" ], however, works great with nested scripts where one script runs or sources another. So, I have massively updated my answer and put my favorite technique at the top of it here now.Idun
P
27

Editor's note: This answer's solution works robustly, but is bash-only. It can be streamlined to
(return 2>/dev/null).

TL;DR

Try to execute a return statement. If the script isn't sourced, that will raise an error. You can catch that error and proceed as you need.

Put this in a file and call it, say, test.sh:

#!/usr/bin/env sh

# Try to execute a `return` statement,
# but do it in a sub-shell and catch the results.
# If this script isn't sourced, that will raise an error.
$(return >/dev/null 2>&1)

# What exit code did that give?
if [ "$?" -eq "0" ]
then
    echo "This script is sourced."
else
    echo "This script is not sourced."
fi

Execute it directly:

shell-prompt> sh test.sh
output: This script is not sourced.

Source it:

shell-prompt> source test.sh
output: This script is sourced.

For me, this works in zsh and bash.

Explanation

The return statement will raise an error if you try to execute it outside of a function or if the script is not sourced. Try this from a shell prompt:

shell-prompt> return
output: ...can only `return` from a function or sourced script

You don't need to see that error message, so you can redirect the output to dev/null:

shell-prompt> return >/dev/null 2>&1

Now check the exit code. 0 means OK (no errors occurred), 1 means an error occurred:

shell-prompt> echo $?
output: 1

You also want to execute the return statement inside of a sub-shell. When the return statement runs it . . . well . . . returns. If you execute it in a sub-shell, it will return out of that sub-shell, rather than returning out of your script. To execute in the sub-shell, wrap it in $(...):

shell-prompt> $(return >/dev/null 2>$1)

Now, you can see the exit code of the sub-shell, which should be 1, because an error was raised inside the sub-shell:

shell-prompt> echo $?
output: 1
Phosphate answered 6/1, 2016 at 20:55 Comment(6)
This fails for me in 0.5.8-2.1ubuntu2 $ readlink $(which sh) dash $ . test.sh This script is sourced. $ ./test.sh This script is sourced.Chaille
POSIX does not specify what return should do at the top level (pubs.opengroup.org/onlinepubs/9699919799/utilities/…). The dash shell treats a return at the top level as exit. Other shells like bash or zsh don't allow return at the top level, which is the feature a technique like this exploits.Phosphate
It works in sh if you remove the $ before the subshell. That is, use (return >/dev/null 2>&1) instead of $(return >/dev/null 2>&1) - but then it stops working in bash.Execrable
@Eponymous: Since dash, where this solution doesn't work, acts as sh on Ubuntu, for instance, this solution doesn't generally work with sh. The solution does work for me in Bash 3.2.57 and 4.4.5 - with or without the $ before (...) (though there's never a good reason for the $).Extern
returning wihout an explcit return value breaks when sourceing the scripts just after a bad-exitted command. Proposed the enhancement edit.Extensity
Even though the return is written in a sourced script, the context in which it gets called is top-level and therefore it should always fail. That it does not is somewhat obviously a bug and may therefore one day be fixed, at which point this will stop working.Aminopyrine
E
21

FWIW, after reading all of the other answers, I came up with following solution for me:

Update: Actually, somebody spotted a since-corrected error in another answer which affected mine, too. I think the update here also is an improvement (see edits if you are curious).

This works for all scripts, which start with #!/bin/bash but might be sourced by different shells as well to learn some information (like settings) which is are kept outside the main function.

According to the comments below, this answer here apparently does not work for all bash variants. Also not for systems, where /bin/sh is based on bash. I. E. it fails for bash v3.x on MacOS. (Currenty I do not know how to solve this.)

#!/bin/bash

# Function definitions (API) and shell variables (constants) go here
# (This is what might be interesting for other shells, too.)

# this main() function is only meant to be meaningful for bash
main()
{
# The script's execution part goes here
}

BASH_SOURCE=".$0" # cannot be changed in bash
test ".$0" != ".$BASH_SOURCE" || main "$@"

Instead of the last 2 lines you can use following (in my opinion less readable) code to not set BASH_SOURCE in other shells and allow set -e to work in main:

if ( BASH_SOURCE=".$0" && exec test ".$0" != ".$BASH_SOURCE" ); then :; else main "$@"; fi

This script-recipe has following properties:

  • If executed by bash the normal way, main is called. Please note that this does not include a call like bash -x script (where script does not contain a path), see below.

  • If sourced by bash, main is only called, if the calling script happens to have the same name. (For example, if it sources itself or via bash -c 'someotherscript "$@"' main-script args.. where main-script must be, what test sees as $BASH_SOURCE).

  • If sourced/executed/read/evaled by a shell other than bash, main is not called (BASH_SOURCE is always different to $0).

  • main is not called if bash reads the script from stdin, unless you set $0 to be the empty string like so: ( exec -a '' /bin/bash ) <script

  • If evaluated by bash with eval (eval "`cat script`" all quotes are important!) from within some other script, this calls main. If eval is run from commandline directly, this is similar to previous case, where the script is read from stdin. (BASH_SOURCE is blank, while $0 usually is /bin/bash if not forced to something completely different.)

  • If main is not called, it does return true ($?=0).

  • This does not rely on unexpected behavior (previously I wrote undocumented, but I found no documentation that you cannot unset nor alter BASH_SOURCE either):

    • BASH_SOURCE is a bash reserved array. But allowing BASH_SOURCE=".$0" to change it would open a very dangerous can of worms, so my expectation is, that this must have no effect (except, perhaps, some ugly warning shows up in some future version of bash).
    • There is no documentation that BASH_SOURCE works outside functions. However the opposite (that it only works in functions) is neither documented. The observation is, that it works (tested with bash v4.3 and v4.4, unfortunately I have no bash v3.x anymore) and that quite too many scripts would break, if $BASH_SOURCE stops working as observed. Hence my expectation is, that BASH_SOURCE stays as is for future versions of bash, too.
    • In contrast (nice find, BTW!) consider ( return 0 ), which gives 0 if sourced and 1 if not sourced. This comes a bit unexpected not only for me , and (according to the readings there) POSIX says, that return from subshell is undefined behavior (and the return here is clearly from a subshell). Perhaps this feature eventually gets enough widespread use such that it can no more be changed, but AFAICS there is a much higher chance that some future bash version accidental changes the return behavior in that case.
  • Unfortunately bash -x script 1 2 3 does not run main. (Compare script 1 2 3 where script has no path). Following can be used as workaround:

    • bash -x "`which script`" 1 2 3
    • bash -xc '. script' "`which script`" 1 2 3
    • That bash script 1 2 3 does not run main can be considered a feature.
  • Note that ( exec -a none script ) calls main (bash does not pass it's $0 to the script, for this you need to use -c as shown in the last point).

Thus, except for some some corner cases, main is only called, when the script is executed the usual way. Normally this is, what you want, especially because it lacks complex hard to understand code.

Note that it is very similar to the Python code:

if __name__ == '__main__': main()

Which also prevents calling of main, except for some corner cases, as you can import/load the script and enforce that __name__='__main__'

Why I think this is a good general way to solve the challenge

If you have something, which can be sourced by multiple shells, it must be compatible. However (read the other answers), as there is no (easy to implement) portable way to detect the sourceing, you should change the rules.

By enforcing that the script must be executed by /bin/bash, you exactly do this.

This solves all cases but following in which case the script cannot run directly:

  • /bin/bash is not installed or disfunctional (i. E. in a boot environment)
  • If you pipe it to a shell like in curl https://example.com/script | $SHELL
  • (Note: This is only true if your bash is recent enough. This recipe is reported to fail for certain variants. So be sure to check it works for your case.)

However I cannot think about any real reason where you need that and also the ability to source the exactly same script in parallel! Usually you can wrap it to execute the main by hand. Like that:

  • $SHELL -c '. script && main'
  • { curl https://example.com/script && echo && echo main; } | $SHELL
  • $SHELL -c 'eval "`curl https://example.com/script`" && main'
  • echo 'eval "`curl https://example.com/script`" && main' | $SHELL

Notes

Epimenides answered 2/12, 2017 at 22:53 Comment(9)
Tested for ksh and bash-4.3. Nice. It's such a pity your answer will have a hard life given that the other answers already had years collecting up-votes.Chemosynthesis
thank you for this answer. I appreciated the longer, 'less readable' test with the IF statement since it's nice to handle both situations to at least give non-silent failure. In my case I need a script to be sourced or otherwise inform user of their error in not using source.Pony
@Tino: As for "might be sourced by different shells as well": On macOS, where /bin/sh is effectively bash in POSIX mode, assigning to BASH_SOURCE breaks your script. In other shells (dash, ksh, zsh), invoking your script by passing it as a file argument directly to the shell executable malfunctions (e.g., zsh <your-script> will make your script mistakenly think it is sourced). (You already mention that piping the code malfunctions, in all shells.)Extern
@Tino: As an aside: While . <your-script> (sourcing) does work from all POSIX-like shells in principle, it only makes sense if the script was explicitly written to use POSIX features only, so as to prevent features specific to one shell from breaking execution in other shells; using a Bash shebang line (rather than #!/bin/sh) is therefore confusing - at least without a conspicuous comment. Conversely, if your script is meant to be run from Bash only (even if only by virtue of not considering what features may not be portable), it's better to refuse execution in non-Bash shells.Extern
@Extern to your first comment: Running bash with export POSIXLY_CORRECT=: I cannot spot any problem currently. I have no macOS, though, so thanks for noting. And to both comments: Actually my expectation is, that main is only written for bash and not meant for other shells (other shells need only be able to parse main, not to execute it correctly). This way other shells can still source the script to "learn" something from it, like some shared hardcoded settings (yuck!) etc. outside of main (left away in the example). It might come handy, YMMVEpimenides
macOS, as of v10.14.6, uses v3.2.57 of Bash, and you can reproduce the problem there as follows: bash --posix -c 'echo before; BASH_SOURCE=hi; echo after' (prints just before); Bash v4.4.23, for instance, doesn't have that problem. As for your both comments response: I encourage you to make that clear in your answer, ideally with amended code that prevents invocation of main from other shells or at least emits a warning first.Extern
@Extern Edited, thanks for noting! As I have no idea how to test this myself, does the 2nd variant if ( BASH_SOURCE=".$0" && exec test ".$0" != ".$BASH_SOURCE" ); then :; else main "$@"; fi work with macOS' bash v3.2.57? This uses a subshell, hence might fail, hence might execute main as wanted under bash?Epimenides
@Tino: The subshell always fails in v3.2.57 due to the attempt to assign to $BASH_SOURCE, so main is always executed when you call from Bash / Bash acting as sh - whether you source the script or not.Extern
@Extern Thanks again, added a note that there is a problem. For other readers: When sourced with bash v3.x it should not execute main, but it does this in this case! And when sourced by /bin/sh, which is bash --posix, the same happens in this case, and that is plain wrong as well.Epimenides
A
13

This works later on in the script and does'nt depend on the _ variable:

## Check to make sure it is not sourced:
Prog=myscript.sh
if [ $(basename $0) = $Prog ]; then
   exit 1  # not sourced
fi

or

[ $(basename $0) = $Prog ] && exit
Apprehensible answered 31/5, 2010 at 7:59 Comment(3)
I think this answer is one of the few POSIX compliant here. With the obvious downsides being that you have to know the filename and it doesn't work if both scripts have the same filename.Bathyal
Good simple answer even though it does require the script filename.Collectivism
How about this: is_sourced() { case $(basename "${0#-}") in sh|bash|ash|dash|ksh) return 0;; *) return 1;; esac }Mores
U
6

I will give a BASH-specific answer. Korn shell, sorry. Suppose your script name is include2.sh ; then make a function inside the include2.sh called am_I_sourced. Here's my demo version of include2.sh:

am_I_sourced()
{
  if [ "${FUNCNAME[1]}" = source ]; then
    if [ "$1" = -v ]; then
      echo "I am being sourced, this filename is ${BASH_SOURCE[0]} and my caller script/shell name was $0"
    fi
    return 0
  else
    if [ "$1" = -v ]; then
      echo "I am not being sourced, my script/shell name was $0"
    fi
    return 1
  fi
}

if am_I_sourced -v; then
  echo "Do something with sourced script"
else
  echo "Do something with executed script"
fi

Now try to execute it in many ways:

~/toys/bash $ chmod a+x include2.sh

~/toys/bash $ ./include2.sh 
I am not being sourced, my script/shell name was ./include2.sh
Do something with executed script

~/toys/bash $ bash ./include2.sh 
I am not being sourced, my script/shell name was ./include2.sh
Do something with executed script

~/toys/bash $ . include2.sh
I am being sourced, this filename is include2.sh and my caller script/shell name was bash
Do something with sourced script

So this works without exception, and it is not using the brittle $_ stuff. This trick uses BASH's introspection facility, i.e. built-in variables FUNCNAME and BASH_SOURCE; see their documentation in bash manual page.

Only two caveat:

1) the call to am_I_called must take place in the sourced script, but not within any function, lest ${FUNCNAME[1]} returns something else. Yeah...you could have checked ${FUNCNAME[2]} -- but you just make your life harder.

2) function am_I_called must reside in the sourced script if you want to find out what the name of the file being included.

Uncommonly answered 12/9, 2012 at 21:9 Comment(1)
Clarification: This feature requires BASH version 3+ to work. In BASH 2, FUNCNAME is a scalar variable instead of an array. Also BASH 2 does not have BASH_SOURCE array variable.Uncommonly
I
5

The most beautiful way to detect if a Bash script is being executed or sourced (imported)

I really think this is the most beautiful way to do it:

From my if__name__==__main___check_if_sourced_or_executed_best.sh file in my eRCaGuy_hello_world repo:

#!/usr/bin/env bash

main() {
    echo "Running main."
    # Add your main function code here
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    # This script is being run.
    __name__="__main__"
else
    # This script is being sourced.
    __name__="__source__"
fi

# Only run `main` if this script is being **run**, NOT sourced (imported)
if [ "$__name__" = "__main__" ]; then
    echo "This script is being run."
    main "$@"
else
    echo "This script is being sourced."
fi

References:

  1. See also my other answer here for additional details on the above technique, including showing the run output: What is the bash equivalent to Python's if __name__ == '__main__'?
  2. This answer where I first learned about "${BASH_SOURCE[0]}" = "$0"

You can also explore the following alternatives if you like, but I prefer to use the code chunk above.

Important: Using the "${FUNCNAME[-1]}" technique does not properly handle nested scripts, where one script calls or sources another, whereas the if [ "${BASH_SOURCE[0]}" = "$0" ] technique does. That's another huge reason to use if [ "${BASH_SOURCE[0]}" = "$0" ] instead.

4 ways to determine whether a bash script is being sourced or executed

I have read a bunch of answers all over the place on this and a few other questions, and have come up with 4 ways I'd like to summarize and put in one place.

if __name__ == "__main__":

See: What does if __name__ == "__main__": do? for what that does in Python.

  1. You can see a full demonstration of all 4 techniques below in my check_if_sourced_or_executed.sh script in my eRCaGuy_hello_world repo.
  2. You can see one of the techniques in-use in my advanced bash program with help menu, argument parsing, main function, automatic execute vs source detection (akin to if __name__ == "__main__": in Python), etc, see my demo/template program in this list here. It is currently called argument_parsing__3_advanced__gen_prog_template.sh, but if that name changes in the future I'll update it in the list at the link just above

Anyway, here are the 4 Bash techniques:

  1. Technique 1 (can be placed anywhere; handles nested scripts): See: https://unix.stackexchange.com/questions/424492/how-to-define-a-shell-script-to-be-sourced-not-run/424495#424495

    if [ "${BASH_SOURCE[0]}" -ef "$0" ]; then
        echo "  This script is being EXECUTED."
        run="true"
    else
        echo "  This script is being SOURCED."
    fi
    
  2. Technique 2 [My favorite technique] (can be placed anywhere; handles nestes scripts): See this type of technique in-use in my most-advanced bash demo script yet, here: argument_parsing__3_advanced__gen_prog_template.sh, near the bottom.

    Modified from: What is the bash equivalent to Python's `if __name__ == '__main__'`?

    if [ "${BASH_SOURCE[0]}" == "$0" ]; then
        echo "  This script is being EXECUTED."
        run="true"
    else
        echo "  This script is being SOURCED."
    fi
    
  3. Technique 3 (requires another line which MUST be outside all functions): Modified from: How to detect if a script is being sourced

    # A. Place this line OUTSIDE all functions:
    (return 0 2>/dev/null) && script_is_being_executed="false" || script_is_being_executed="true"
    
    # B. Place these lines anywhere
    if [ "$script_is_being_executed" == "true" ]; then
        echo "  This script is being EXECUTED."
        run="true"
    else
        echo "  This script is being SOURCED."
    fi
    
  4. Technique 4 [Limitation: does not handle nested scripts!] (MUST be inside a function): Modified from: How to detect if a script is being sourced
    and Unix & Linux: How to define a shell script to be sourced not run.

    if [ "${FUNCNAME[-1]}" == "main" ]; then
        echo "  This script is being EXECUTED."
        run="true"
    elif [ "${FUNCNAME[-1]}" == "source" ]; then
        echo "  This script is being SOURCED."
    else
        echo "  ERROR: THIS TECHNIQUE IS BROKEN"
    fi
    
    1. This is where I first learned about the ${FUNCNAME[-1]} trick: @mr.spuratic: How to detect if a script is being sourced - he learned it from Dennis Williamson apparently.

See also:

  1. [my answer] What is the bash equivalent to Python's if __name__ == '__main__'?
  2. [my answer] Unix & Linux: How to define a shell script to be sourced not run
Idun answered 11/1, 2022 at 5:32 Comment(0)
D
3

I would like to suggest a small correction to Dennis' very helpful answer, to make it slightly more portable, I hope:

[ "$_" != "$0" ] && echo "Script is being sourced" || echo "Script is a subshell"

because [[ isn't recognized by the (somewhat anal retentive IMHO) Debian POSIX compatible shell, dash. Also, one may need the quotes to protect against filenames containing spaces, again in said shell.

Devout answered 30/5, 2010 at 22:22 Comment(0)
Y
2

$_ is quite brittle. You have to check it as the first thing you do in the script. And even then, it is not guaranteed to contain the name of your shell (if sourced) or the name of the script (if executed).

For example, if the user has set BASH_ENV, then at the top of a script, $_ contains the name of the last command executed in the BASH_ENV script.

The best way I have found is to use $0 like this:

name="myscript.sh"

main()
{
    echo "Script was executed, running main..."
}

case "$0" in *$name)
    main "$@"
    ;;
esac

Unfortunately, this way doesn't work out of the box in zsh due to the functionargzero option doing more than its name suggests, and being on by default.

To work around this, I put unsetopt functionargzero in my .zshenv.

Yaekoyael answered 4/4, 2011 at 22:18 Comment(0)
R
2

Not exactly what the OP wanted, but I often find myself needing to source a script just to load its functions (i.e. as a library). For example, for benchmarking or testing purposes.

Here's a design that works in all shells (including POSIX):

  • Wrap all your top-level actions in a run_main() function.
  • Have your sourced script check for an initial --no-run argument which doesn't perform any actions; without --no-run, it can call run_main.
  • source the script using:
set -- --no-run "$@"
. script.sh
shift

The problem with . or source is that it's impossible to pass arguments to the script portably. POSIX shells ignore arguments to . and pass the caller's "$@" no matter what.

Ratcliffe answered 27/7, 2021 at 9:28 Comment(1)
Very interesting answer. Trying to achieve that was the reason why I was looking for a solution to detect if a script was sourced. Thank you.Scenario
A
1

I don't think there is any portable way to do this in both ksh and bash. In bash you could detect it using caller output, but I don't think there exists equivalent in ksh.

Autosuggestion answered 21/4, 2010 at 15:21 Comment(1)
$0 works in bash, ksh93, and pdksh. I don't have ksh88 to test.Yaekoyael
C
1

I followed mklement0 compact expression.

That's neat, but I noticed that it can fail in the case of ksh when invoked as this:

/bin/ksh -c ./myscript.sh

(it thinks it's sourced and it's not because it executes a subshell) But the expression will work to detect this:

/bin/ksh ./myscript.sh

Also, even if the expression is compact, the syntax is not compatible with all shells.

So I ended with the following code, which works for bash,zsh,dash and ksh

SOURCED=0
if [ -n "$ZSH_EVAL_CONTEXT" ]; then 
    [[ $ZSH_EVAL_CONTEXT =~ :file$ ]] && SOURCED=1
elif [ -n "$KSH_VERSION" ]; then
    [[ "$(cd $(dirname -- $0) && pwd -P)/$(basename -- $0)" != "$(cd $(dirname -- ${.sh.file}) && pwd -P)/$(basename -- ${.sh.file})" ]] && SOURCED=1
elif [ -n "$BASH_VERSION" ]; then
    [[ $0 != "$BASH_SOURCE" ]] && SOURCED=1
elif grep -q dash /proc/$$/cmdline; then
    case $0 in *dash*) SOURCED=1 ;; esac
fi

Feel free to add exotic shells support :)

Cryostat answered 30/6, 2016 at 16:8 Comment(4)
In ksh 93+u, ksh ./myscript.sh works fine for me (with my statement) - what version are you using?Extern
I fear there is no way to reliably determine if a script is being sourced using POSIX-features only: your attempt assumes Linux (/proc/$$/cmdline) and focuses on dash only (which also acts as sh on Ubuntu, for instance). If you're willing to make certain assumptions, you can examine $0 for a reasonable - but incomplete - test that is portable.Extern
++ for the basic approach, though - I've taken the liberty to adapt it for what I think is the best portable approximation of supporting sh / dash as well, in an addendum to my answer.Extern
Since "compatible with all shells" and "exotic shells" is mentioned, ${0##*/} and $() aren't portable to at least one older Bourne shell (that I still have to use, even if it is a shame that it is necessary): echo ${0##*/} yields bad substitution, and echo $(dirname $0) gives syntax error: '(' unexpected. echo $0 gives -sh.Sexism
J
1

The fix for this issue is not to write code that needs to know such a thing in order to behave correctly. And the way to do that is to put the code into a function, and not into the mainline of a script that needs to be sourced.

Code inside a function can just return 0 or return 1. This terminates just the function, so that control returns to whatever invoked the function.

This works whether the function is called from the mainline of a sourced script, from the mainline of a top-level script, or from another function.

Use sourcing to bring in "library" scripts that only define functions and perhaps variables, but don't actually execute any other top-level commands:

. path/to/lib.sh # defines libfunction
libfunction arg

or else:

path/to/script.sh arg # call script as a child process

and not:

. path/to/script.sh arg  # shell programming anti-pattern
Jenniejennifer answered 21/1, 2021 at 9:47 Comment(0)
S
1

A small addition to the @mklement0 answer. This is the custom function I used in my script to determine whether it is sourced or not:

replace_shell(){
   if [ -n "$ZSH_EVAL_CONTEXT" ]; then 
      case $ZSH_EVAL_CONTEXT in *:file*) echo "Zsh is sourced";; esac
   else
      case ${0##*/} in sh|dash|bash) echo "Bash is sourced";; esac
   fi
}

In a function, the output of "$ZSH_EVAL_CONTEXT" for zsh is toplevel:file:shfunc and not just toplevel:file during sorcing; thus, *:file* should fix this issue.

Sunlit answered 12/5, 2022 at 8:13 Comment(0)
S
0

I needed a one-liner that works on [mac, linux] with bash.version >= 3 and none of these answers fit the bill.

[[ ${BASH_SOURCE[0]} = $0 ]] && main "$@"
Skolnik answered 27/2, 2015 at 22:52 Comment(0)
O
0

Straight to the point: you must evaluate if the variable "$0" is equal to the name of your Shell.


Like this:

#!/bin/bash

echo "First Parameter: $0"
echo
if [[ "$0" == "bash" ]] ; then
    echo "The script was sourced."
else
    echo "The script WAS NOT sourced."
fi


Via SHELL:

$ bash check_source.sh 
First Parameter: check_source.sh

The script WAS NOT sourced.

Via SOURCE:

$ source check_source.sh
First Parameter: bash

The script was sourced.



It's pretty hard to have a 100% portable way of detecting if a script was sourced or not.

Regarding my experience (7 years with Shellscripting), the only safe way (not relying on environment variables with PIDs and so on, which is not safe due to the fact that it is something VARIABLE), you should:

  • extend the possibilities from your if
  • using switch/case, if you want to.

Both options cannot be auto scaled, but it is the safer way.



For example:

when you source a script via an SSH session, the value returned by the variable "$0" (when using source), is -bash.

#!/bin/bash

echo "First Parameter: $0"
echo
if [[ "$0" == "bash" || "$0" == "-bash" ]] ; then
    echo "The script was sourced."
else
    echo "The script WAS NOT sourced."
fi

OR

#!/bin/bash

echo "First Parameter: $0"
echo
if [[ "$0" == "bash" ]] ; then
    echo "The script was sourced."
elif [[ "$0" == "-bash" ]] ; then
    echo "The script was sourced via SSH session."
else
    echo "The script WAS NOT sourced."
fi
Oza answered 11/5, 2017 at 15:41 Comment(2)
Downvoted, as this is plain wrong: /bin/bash -c '. ./check_source.sh' gives The script WAS NOT sourced.. Same bug: ln -s /bin/bash pumuckl; ./pumuckl -c '. ./check_source.sh' -> The script WAS NOT sourced.Epimenides
Your downvote has changed the whole scenario and made a great contribution, Tino. Thanks!Oza
T
0

I ended up with checking [[ $_ == "$(type -p "$0")" ]]

if [[ $_ == "$(type -p "$0")" ]]; then
    echo I am invoked from a sub shell
else
    echo I am invoked from a source command
fi

When use curl ... | bash -s -- ARGS to run remote script on-the-fly, the $0 will be just bash instead of normal /bin/bash when run actual script file, so I use type -p "$0" to show full path of bash.

test:

curl -sSL https://github.com/jjqq2013/bash-scripts/raw/master/common/relpath | bash -s -- /a/b/c/d/e /a/b/CC/DD/EE

source <(curl -sSL https://github.com/jjqq2013/bash-scripts/raw/master/common/relpath)
relpath /a/b/c/d/e /a/b/CC/DD/EE

wget https://github.com/jjqq2013/bash-scripts/raw/master/common/relpath
chmod +x relpath
./relpath /a/b/c/d/e /a/b/CC/DD/EE
Tyrosine answered 24/7, 2018 at 16:41 Comment(0)
G
0

This is a spin off from some other answers, regarding "universal" cross shell support. This is admittedly very similar to https://mcmap.net/q/12867/-how-to-detect-if-a-script-is-being-sourced in particular, though slightly different. The weakness with this, is that a client script must respect how to use it (i.e. by exporting a variable first). The strength is that this is simple and should work "anywhere". Here's a template for your cut & paste pleasure:

# NOTE: This script may be used as a standalone executable, or callable library.
# To source this script, add the following *prior* to including it:
# export ENTRY_POINT="$0"

main()
{
    echo "Running in direct executable context!"
}

if [ -z "${ENTRY_POINT}" ]; then main "$@"; fi

Note: I use export just be sure this mechanism can be extended into sub processes.

Gyatt answered 27/11, 2019 at 14:20 Comment(0)
R
0

Yet another solution (depends on readlink from GNU coreutils):

if [ "$(readlink -f "$(command -v "$0")")" != "$(readlink -f /proc/$$/exe)" ]; then
  echo "Is executed"
fi

This compares:

  1. The current command name (if executed: script name, if sourced: the shell interpreter)
  2. The current executable (always the shell interpreter)
Reich answered 17/4, 2023 at 16:52 Comment(0)
Y
0

This should be sh compliant, specifically compliant with busybox ash (which doesn't have the above handy bash-esque one-liners).

This has the same idea as jim mcnamara's solution above, but instead of hardcoding the filename as a variable, you fetch it, and compare basenames. The code comes from how to get a sourced filename in busybox ash.

THIS_FILE="$(lsof | grep '^'$$ | tail -n1 | awk '{print $3}')"
[ "${0##*/}" != "${THIS_FILE##*/}" ] && sourced='yes' || sourced='no'
Yacketyyak answered 2/11, 2023 at 19:20 Comment(0)
T
0

Seems to work for bash, zsh, ksh & dash.

I did see an issue with sourcing detection when sourcing from a file executed by dash.

executingName="${0##*/}"
separator='+'
SHS="${separator?}sh${separator?}dash${separator?}-sh${separator?}-dash${separator?}"
sourced="${BASH_VERSION:+$( 
  ( 2>/dev/null return 0 ) || test 0 -eq ${??} ;
)${??
}}${ZSH_VERSION:+$(
  test "${ZSH_EVAL_CONTEXT##*:file}" != "${ZSH_EVAL_CONTEXT-}" ;
)${??
}}${KSH_VERSION:+$(
  test "${executingName?
    }" = "${0-}" -o "${executingName?
    }" != "${.sh.file##*/}"
)${??}}$(
  test "${SHS#*${separator?}${executingName?
    }${separator?}}" != "${SHS?
    }" && printf '%s' "${??}"
)"
printf '%9s' "$(
  test 0 -ne ${sourced:-8} && printf "unsourced" || printf "sourced"
)"

Mostly based on https://mcmap.net/q/12867/-how-to-detect-if-a-script-is-being-sourced w/ "cheatsheet" for info about parameter expansion https://steinbaugh.com/posts/posix.html , and changing the case-esac into a substitution i saw over at https://stackoverflow.com/a/43912605 .

Thomajan answered 1/12, 2023 at 2:31 Comment(0)
N
0

I upvoted a couple of very good answers and ended up with these 2 lines for bash:

function do_not_source { [[ "${FUNCNAME[-1]}" != "source" ]]; }
do_not_source || return 2
Nazario answered 8/2 at 0:31 Comment(0)
H
-1

Use a shebang line and check if it is being Executed instead.

Your script should have a shebang line #!/path/to/shell saying what shell it should run in. Otherwise, you will have other cross shell compatibility issues as well.

Therefore, you only need to check if its being executed by attempting a command that does not work when being sourced.

eg. For a Bash script:

#!/usr/bin/env bash

if (return 0 2>/dev/null); then
    echo "Script was sourced."
fi

This method also works for zsh and sh just change the shebang line.

Habitue answered 7/6, 2022 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.