[英]meta programming in bash/zsh to reload shell script
I have three zsh script,我有三个 zsh 脚本,
meta_zsh.sh
, meta_zsh.sh
,
# meta_zsh.sh
meta_s() {
eval 'echo "${(%):-%x} re-define s()"; s() { echo " calling s() ${(%):-%x}"; }'
}
script_zsh.sh
and script_zsh_2.sh
(the same content) script_zsh.sh
和script_zsh_2.sh
(内容相同)
# script_zsh.sh and script_zsh_2.sh (the same content)
meta_s
s
in zsh execute below commands在 zsh 中执行以下命令
$ . ./meta_zsh.sh; . ./script_zsh.sh; . ./script_zsh_2.sh
outputs输出
./meta_zsh.sh re-define s()
calling s() ./script_zsh.sh
./meta_zsh.sh re-define s()
calling s() ./script_zsh_2.sh
The question is, how to achieve same effect in bash?问题是,如何在 bash 中达到同样的效果?
I tried change to ${(%):-%x}
to ${BASH_SOURCE[0]}
or $0
, but neither works.我尝试将${(%):-%x}
更改为${BASH_SOURCE[0]}
或$0
,但都不起作用。
why bother?何必?
After above meta_xx.sh sourced in ~/.zshrc (~/.bashrc),以上 meta_xx.sh 来源于 ~/.zshrc (~/.bashrc) 之后,
I can type s
in the shell to reload a recently source script, if meta_s
is in it.如果meta_s
在其中,我可以在 shell 中键入s
以重新加载最近的源脚本。
BASH_SOURCE
is actually the stack of callers, with ${BASH_SOURCE[0]}
being the current file, so you can use ${BASH_SOURCE[1]}
: BASH_SOURCE
实际上是调用者堆栈,其中${BASH_SOURCE[0]}
是当前文件,因此您可以使用${BASH_SOURCE[1]}
:
$ cat meta.sh
meta_s() {
eval 'CALLER=${BASH_SOURCE[1]}; echo "$CALLER re-define s()"; s() { echo " calling s() $CALLER"; }'
}
$ cat s1.sh
meta_s
s
$ cat s2.sh
meta_s
s
$ . meta.sh ; . s1.sh ; . s2.sh
s1.sh re-define s()
calling s() s1.sh
s2.sh re-define s()
calling s() s2.sh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.