${BASH_SOURCE[0]} equivalent in zsh? ${BASH_SOURCE[0]} equivalent in zsh? shell shell

${BASH_SOURCE[0]} equivalent in zsh?


${BASH_SOURCE[0]} equivalent in zsh is ${(%):-%N}, NOT $0(as OP said, the latter failed in .zshrc)

Here % indicates prompt expansion on the value,%N indicates "The name of the script, sourced file,or shell function that zsh is currently executing,

whichever was started most recently. If there is none, this is equivalent to the parameter $0."(from man zshmisc)


${(%):-%x} is the closest zsh equivalent to bash's $BASH_SOURCE (and ksh's ${.sh.file}) - not $0.

Tip of the hat to Hui Zheng for providing the crucial pointer and background information in his answer.

It returns the (potentially relative) path of the enclosing script,

  • regardless of whether the script is being sourced or not.
    • specifically, it also works inside initialization/profiles files such as ~/.zshrc (unlike $0, which inexplicably returns the shell's path there).
  • regardless of whether called from inside a function defined in the script or not (unlike $0, which returns the function name inside a function).

The only difference to $BASH_SOURCE I've found is in the following obscure scenario - which may even be a bug (observed in zsh 5.0.5): inside a function nested inside another function in a sourced script, ${(%):-%x} does not return the enclosing script path when that nested function is called (again) later, after having been sourced (returns either nothing or 'zsh').


Background information on ${(%):-%x}:

  • (%):- in lieu of a variable name in a parameter (variable) expansion (${...}) makes escape sequences available that are normally used to represent environmental information in prompt strings, such as used in the PS1 variable to determine the string displayed as the primary interactive prompt.

    • % is an instance of a parameter expansion flag, all of which are listed in man zshexpn under the heading Parameter Expansion Flags.
  • %x is one of the escape sequences that can be used in prompt strings, and it functions as described above; there are many more, such as %d to represent the current dir.

    • man zshmisc lists all available sequences under the heading SIMPLE PROMPT ESCAPES.


If you want to make your script both bash and zsh-compatible you can use ${BASH_SOURCE[0]:-${(%):-%x}}. The resulting value will be taken from BASH_SOURCE[0] when it's defined, and ${(%):-%x}} when BASH_SOURCE[0] is not defined.