如何编写并引用全局Bash脚本,使其满足条件时终止父脚本执行?
解决Bash脚本中复用同意确认逻辑的问题
问题原因
- 直接执行脚本无法访问别名:用
bash do-stuff.sh执行时会启动非交互式子Shell,默认不加载~/.bashrc中的别名配置,因此找不到getConsentToContinue命令。 - Source脚本导致终端关闭:用
source do-stuff.sh执行时,脚本在当前终端Shell环境中运行,get-consent-to-continue.sh里的exit 1会直接终止当前Shell进程,也就是关闭终端。
解决方案
方案一:直接调用检查脚本并判断退出码
无需别名,直接通过检查脚本的退出码控制父脚本执行:
- 保留
get-consent-to-continue.sh内容不变:
echo Would you like to continue [y/n]? read response if [ "${response}" != 'y' ]; then exit 1 fi
- 修改
do-stuff.sh,调用脚本并根据退出码决定是否终止:
#!/usr/bin/env bash # 执行前置任务 echo "Doing initial stuff..." # 调用同意检查脚本,返回非0则终止父脚本 if ! ~/path/to/get-consent-to-continue.sh; then echo "Aborting execution." exit 1 fi # 仅用户输入y时执行后续任务 echo "Doing other stuff..."
执行bash ~/path/to/do-stuff.sh时,若输入非'y',检查脚本以退出码1结束,父脚本捕获后终止自身,但不会影响当前终端(父脚本是独立子Shell进程)。
方案二:将检查逻辑改为Shell函数并导出
把同意检查写成Shell函数,放在~/.bashrc中并导出,让子Shell可访问:
- 在
~/.bashrc中添加函数定义并导出:
getConsentToContinue() { echo "Would you like to continue [y/n]?" read response [ "${response}" != 'y' ] && return 1 } # 导出函数,允许子Shell继承 export -f getConsentToContinue
- 修改
do-stuff.sh,调用函数并判断返回值:
#!/usr/bin/env bash # 执行前置任务 echo "Doing initial stuff..." # 调用函数,返回非0则终止父脚本 getConsentToContinue || { echo "Aborting execution."; exit 1; } # 后续任务 echo "Doing other stuff..."
执行bash ~/path/to/do-stuff.sh时,子Shell会继承导出的函数,用户输入非'y'时函数返回1,父脚本执行exit 1终止自身,终端不受影响。
注意事项
- 方案二修改
~/.bashrc后,需执行source ~/.bashrc或重启终端让配置生效。 - 两种方案均避免了在当前终端Shell中执行
exit,既实现父脚本终止,又不会关闭终端。
内容的提问来源于stack exchange,提问作者friend.code
相关产品推荐
相关产品推荐

