Search code examples
shellunixdash-shell

How can I find the path to a script being sourced in dash?


I am trying to have a sourced shell script determine its own location, and I have found that this is a difficult task for dash.

In bash, sh, and csh, I can use: $_.

In fish, I can use (status -f).

In dash, I have had no luck...

I have tried sourcing the path.sh file shown below with the following results:

# path.sh
called=$_
echo called:      $called
echo underscore:  $_
echo zero:        $0
echo dash_source: $DASH_SOURCE
echo bash_source: $BASH_SOURCE

dash -c ". path.sh"

outputs:

called:      /usr/local/bin/dash
underscore:  /usr/local/bin/dash
zero:        dash
dash_source:
bash_source:

How can I get the path to path.sh in dash?


Solution

  • There does not appear to be any portable (POSIX-standard) way to do this.

    POSIX refers to sourcing as "dot scripts." While several other parts of the shell language reference do discuss "dot scripts," none of these instances appear to provide any way to find out the path to the currently-executing dot script. In particular, $0 is reserved for "shell scripts" which are a different thing from "dot scripts." The word "source" does not appear on the page in any capitalization or as part of any larger word (so no $BASH_SOURCE-like thing). None of the standard environment variables which affect the shell seem relevant either. I'm going to say this is not possible within the POSIX spec. Since Dash follows POSIX quite closely, it is unlikely to have a Dashism for this specific case (if it was going to do that, it would've borrowed $BASH_SOURCE or created an analogous variable).