cat >file1.sh <<'EOF_FILE1'
echo 'before source'
source 'file2.sh'
echo 'after source'
func1
EOF_FILE1
cat >file2.sh <<'EOF_FILE2'
echo 'test script'
func1() {
echo 'func1 starts'
exit
}
exit
EOF_FILE2
bash file1.sh
预期输出是:
before source
test script
after source
func1 starts
实际输出是:
before source
test script
由于以下原因,“后源”丢失exit
命令。有没有办法解决这个问题,因为我无法删除exit
从代码中?
鉴于best方法是编写旨在获取而不是执行时考虑到该用例的脚本,如果您出于某种原因无法这样做,您可能会考虑alias
ing exit
to return
之前source
命令,如下:
shopt -s expand_aliases # enable alias expansion (off by default in noninteractive shells)
alias exit=return # ...and alias 'exit' to 'return'
source 'file2.sh' # source in your file which incorrectly uses 'exit' at top-level
unalias exit # disable the alias...
echo 'after source'
func1
如果你想要exit
为了在调用该函数时仍然生效,事情可以变得更复杂一些:
maybe_exit() {
local last_retval=$? # preserve exit's behavior of defaulting to $?
[[ $do_not_really_exit ]] && return # abort if flag is set
(( $# )) && exit "$@" # if arguments are given, pass them through
exit "$last_retval" # otherwise, use the $? we captured above
}
shopt -s expand_aliases # enable alias expansion (off by default in noninteractive shells)
alias exit=maybe_exit # ...and alias 'exit' to 'maybe_exit'
do_not_really_exit=1 # set a flag telling maybe_exit not to really exit
source 'file2.sh' # source in your file which incorrectly uses 'exit' at top-level
unset do_not_really_exit # clear that flag...
unalias exit # disable the alias...
echo 'after source'
func1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)