title: Get target name of hard link in bash (ie BASH_SOURCE)
body: <pre><code>#!/bin/bash
  dir_self () {
      local source="${BASH_SOURCE[$1]}"
      while [ -h "$source" ]; do # resolve $source until the file is no longer a symlink
        dir="$( cd -P "$( dirname "$source" )" &amp;&amp; pwd )"
        source="$(readlink "$source")"
        [[ $source != /* ]] &amp;&amp; source="$dir/$source" # if $source was a relative symlink, we need to resolve it relative to the path where the symlink file was located
      done
      local dir="$( cd -P "$( dirname "$source" )" &amp;&amp; pwd )"
      printf $dir
  }
  #source lib.bash,function,file, hard links return as link location, soft links as target
  dir_self_file () {
      local num=2
      if [[ -n $1 ]];then
          num=3
      fi
      dir_self $num
  }
  </code></pre>
  
  <p>I am using the above functions for determining the directory of a file that is sourcing a <code>lib.bash</code> containing said functions (not the directory of the executing file though that isn't relevant). </p>
  
  <p>Considering the following directory structure:</p>
  
  <pre><code>ln_s-&gt;dir/ln_targ
  ln_h-&gt;dir/ln_targ
  dir/ln_targ
  lib.bash
  </code></pre>
  
  <p>It is usable in the following way:</p>
  
  <pre><code>. $LIB_DIR/lib.bash
  echo $(dir_self_file)
  </code></pre>
  
  <p>In <code>ln_h</code> it will echo the directory of <code>ln_h</code> while in <code>ln_s</code> it will echo the directory of <code>dir/ln_targ</code>.</p>
  
  <p>In theory I would like to be able to get all relevant directories with regards to the context provided by this example, ie:</p>
  
  <pre><code>1) The directory of the sym link
  2) The directory of the hard link
  3) The directory of the target
  </code></pre>
  
  <p>As you can see though, the input to the <code>dir_self</code> provided by <code>BASH_SOURCE</code> specifies either one or the other. </p>
  
  <p>Is there a way to retrieve all the specified values with bash?</p>