bash ksh
Updated Fri, 20 May 2022 22:19:29 GMT

How to detect if a script is being sourced

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?


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).

Comments (5)

  • +0 – 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. — Apr 04, 2011 at 22:14  
  • +0 – This will also not work if you use bash to execute the script, e.g. $ bash then the $_ would be /bin/bash instead of ./, which is the case you expect, when the script is invoked in this way: $ ./ In any case detecting with $_ is a problem. — Sep 12, 2012 at 20:43  
  • +2 – Additional tests could be included to check for those invocation methods. — Feb 19, 2013 at 01:33  
  • +8 – Unfortunely, that's wrong! see my answer — Apr 11, 2014 at 11:33  
  • +0 – 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. — Mar 02, 2016 at 04:47