2

In Bash, the correct way to get the full path to a shell script is ${BASH_SOURCE[0]}, since $0 returns bash if the script is being sourced. For example, try running this in your terminal:

source <(echo 'echo $0')

It will print bash.

Does anyone know how to do this for Bourne shell scripts? For example, what would be the contents of a script foo such that if I typed this:

sh -c '. foo'

it would output the full path to the script?

James Ko
  • 32,215
  • 30
  • 128
  • 239
  • Well, I put `foo` in my path and if it contains `echo ${BASH_SOURCE[0]}` I get it's path echoed. – nsilent22 Feb 19 '16 at 20:35
  • 1
    @nsilent22 Yes, that's true. But how would you do it for scripts written in **sh**? `BASH_SOURCE` is specific to Bash. – James Ko Feb 19 '16 at 20:37
  • 1
    Crossposting: http://unix.stackexchange.com/q/264438/74329 – Cyrus Feb 19 '16 at 20:46
  • Oh... sorry. I didn't read carefully enough. – nsilent22 Feb 19 '16 at 21:00
  • 3
    To note, '/bin/sh' does not necessarily mean the "Bourne shell". In fact it's almost guaranteed not to be, as Bourne is pretty ancient. On modern system, '/bin/sh' is usually a link to bash, dash, csh, ksh, etc. I would try doing `ls -l /bin/sh` or `/bin/sh -v` or `/bin/sh --version` to see what shell you're really dealing with. – kmiles Feb 19 '16 at 21:35
  • Unfortunately, there is no POSIX-compliant way to do what you want; see [this answer](http://stackoverflow.com/a/29835459/45375) of mine for the gory details. – mklement0 Feb 21 '16 at 22:43

0 Answers0