gpt4 book ai didi

bash source 文件末尾有一个退出命令

转载 作者:行者123 更新时间:2023-11-29 09:45:33 24 4
gpt4 key购买 nike

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 命令,“after source”丢失了。有没有办法解决这个问题,因为我无法从代码中删除 exit

最佳答案

虽然最好的方法是编写旨在获取而不是执行的脚本,但如果您出于某种原因不能这样做,您可以考虑 source命令之前将exit别名return,如下所示:

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

关于bash source 文件末尾有一个退出命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52063180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com