首页 > 解决方案 > 我如何为子进程应用“set -e”?

问题描述

我在我的项目中使用 bash shell 脚本。

主脚本调用了很多子脚本,但有时子脚本有错误。我希望脚本立即停止。

我找到了-errexit选择。它对我有用。

有限制。我无法编辑子脚本。另外,我不想碰 exec 行。

下面是例子。

#!/bin/bash

# do something

exec bash test.sh

测试.sh

#!/bin/bash

cat as.txt  # error
cat ab.txt  # run

我不想cat ab.txt被跑。

我知道,exex bash -e test.sh会跑。但真正的项目代码是这样的,触摸 exec 行是危险的。

exec "$@"

我不能指望是什么$@

如果我写set -e“做某事”,它不适用于子进程(test.sh)。

我可以更改默认选项脚本,例如~/.bashrc?如何为子进程应用 shell 选项?

请帮我!

标签: bashshellsh

解决方案


我使用了一个类似的示例,并且在 cat 命令未成功后,带有 do something 的脚本立即退出。

doSome.sh

#!/bin/bash

exec bash test.sh

测试.sh

#!/bin/bash

cat text.txt
touch newfile

输出:

命令输出

也许你不需要使用set -e

编辑:

该文件已创建:

$ ll newfile
-rw-r--r-- 1 0000 0000 0 Sep 14 13:57 newfile

并且当替换touch newfilecat操作时,它确实会继续运行并且问题仍然存在。

一个可行的解决方案可能是在每行基础上添加错误处理:

测试.sh

#!/bin/bash

cat text.txt || exit 1
cat nofile.txt || exit 1

推荐阅读