How can I source a bash script containing BASH_SOURCE from zsh shell?

5,015

Instead of doing . /path/to/that/script.bash, do:

BASH_SOURCE=/path/to/that/script.bash emulate ksh -c '. "$BASH_SOURCE"'

emulate ksh -c '...' runs the code in ksh emulation (so that for instance, array indices start at 0 like in bash) and also makes sure all functions defined within inherit that emulation mode.

$BASH_SOURCE in bash refers to the file being sourced, so we preseed that variable with the path of the script.

The zsh equivalent of that bash code would be:

export SOME_VARIABLE=$0:h:P

(:h giving the head like in csh (the equivalent of dirname), and :P the equivalent of GNU readlink -f).

In any case, that

SOME_VARIABLE=$(readlink -f $(dirname ${BASH_SOURCE[0]}))

Code is incorrect in bash where you'd need:

SOME_VARIABLE=$(
  readlink -f -- "$(dirname -- "$BASH_SOURCE")"
)

And note that even then it wouldn't work if the dirname of $BASH_SOURCE ended in newline characters before or after readlink -f.

Share:
5,015

Related videos on Youtube

rual93
Author by

rual93

Updated on September 18, 2022

Comments

  • rual93
    rual93 over 1 year

    I have a bash script that looks like this:

    ...
    SOME_VARIABLE=$(readlink -f $(dirname ${BASH_SOURCE[0]}))
    export SOME_VARIABLE
    ...
    

    I need to source it from a zsh shell as I need to have all the environment variables it defines.

    The issue is that I get this error message because of BASH_SOURCE:

    dirname: missing operand
    Try 'dirname --help' for more information.
    readlink: missing operand
    Try 'readlink --help' for more information.
    Invalid location:
    

    Constraints: I cannot modify the script.

    Question: Can I source a bash script containing BASH_SOURCE from zsh?

    • Admin
      Admin over 5 years
      Source it from a bash shell, then start the zsh shell.
    • Admin
      Admin over 5 years
      . <(awk '{gsub(/\${BASH_SOURCE\[0\]}/, FILENAME); print}' /path/to/the/bash/script)
    • Admin
      Admin over 5 years
      @mosvy that works for me, I would mark it as accepted if it was an answer instead of a comment