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?
Best Answer
Instead of doing
. /path/to/that/script.bash
, do:emulate ksh -c '...'
runs the code inksh
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
inbash
refers to the file being sourced, so we preseed that variable with the path of the script.The
zsh
equivalent of thatbash
code would be:(
:h
giving the head like in csh (the equivalent ofdirname
), and:P
the equivalent of GNUreadlink -f
).