title: How to determine if a shell script file is sourced in Bash
body: <p>I want to how to determine if a script file is executed or sourced.</p>
  
  <p>For example,</p>
  
  <pre><code># Shell script filename build.sh
  if [ "x$0" = "xbash" ]; then
      echo "I am sourced by Bash"
  else
      echo "I am executed by Bash"
  fi
  </code></pre>
  
  <p>If I typed</p>
  
  <pre><code>source build.sh
  </code></pre>
  
  <p>it would output <em>I am sourced by Bash</em>.</p>
  
  <p>If I typed</p>
  
  <pre><code>./build.sh
  </code></pre>
  
  <p>it would output <em>I am executed by Bash</em>.</p>
  
  <p>Currently, I use $0 to do this. Is there a better idea?</p>
  
  <p>Inspired by Tripeee, I found a better way:</p>
  
  <pre><code>#!/bin/bash
  
  if [ "x$(awk -F/ '{print $NF}' &lt;&lt;&lt; $0)" = 'xcdruntime' ]; then
      echo Try to source me, not execute me.
  else
      cd /opt/www/app/pepsi/protected/runtime
  fi
  </code></pre>