bash - bash source 一个结尾有退出命令的文件
问题描述
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
从代码中删除?
解决方案
虽然最好的方法是编写旨在获取而不是在考虑该用例的情况下执行的脚本,但如果您出于某种原因不能这样做,您可以考虑alias
在exit
命令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
in 在调用该函数时仍然生效,则可以使事情变得更复杂一些:
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
推荐阅读
- python - 部分应用/和/或/柯里化的装饰器:如何确定是否提供了强制参数?
- html - UIPrintPageRenderer 破坏不同页面上的内容并跳过部分页面
- swift - 警告说当我尝试打开一个不允许的 URL 时它被阻止
- node.js - Cpanel 中的 Node.js(Express)Restful API 应用程序不起作用(API)?得到 503 服务不可用
- arrays - 除了不变性之外,字符串与 char 数组相比的优势
- c# - 传递 IOptions
启动配置中的方法 - javascript - 如何更改 Vuetify v-autocomplete 菜单边框半径样式?
- python - Matplotlib 用圆圈孵化:如何抑制“截断”圆圈的显示?
- swift - 您需要 SQLite 的服务器吗
- python - 无法隐藏 Dash DataTable 过滤器列