出错时停止调用脚本

lam*_*988 4 error-handling bash

我有2个shell脚本,即脚本A和脚本B.我有两个"set -e",告诉他们在出错时停止.

但是,当脚本A调用脚本B和脚本B出现错误并停止时,脚本A没有停止.

当子脚本死亡时,我能阻止母脚本什么?

Sha*_*hin 5

它应该按照你的期望工作.例如:

mother.sh:

#!/bin/bash
set -ex
./child.sh
echo "you should not see this (a.sh)"
Run Code Online (Sandbox Code Playgroud)

child.sh:

#!/bin/bash
set -ex
ls &> /dev/null # good cmd
ls /path/that/does/not/exist &> /dev/null # bad cmd
echo "you should not see this (b.sh)"
Run Code Online (Sandbox Code Playgroud)

致电mother.sh:

[me@home]$ ./mother.sh
++ ./child.sh
+++ ls
+++ ls /path/that/does/not/exist
Run Code Online (Sandbox Code Playgroud)

为什么它不适合你?

如果你-e在shabang line(#!/bin/bash -e)中指定并直接传递脚本bash将其视为注释,那么它将无法按预期工作的一种可能情况.

例如,如果我们mother.sh改为:

#!/bin/bash -ex
./child.sh
echo "you should not see this (a.sh)"
Run Code Online (Sandbox Code Playgroud)

请注意它的行为方式取决于您调用它的方式:

[me@home]$ ./mother.sh
+ ./child.sh
+ ls
+ ls /path/that/does/not/exist

[me@home]$ bash mother.sh  
+ ls
+ ls /path/that/does/not/exist
you should not see this (a.sh)
Run Code Online (Sandbox Code Playgroud)

set -e在脚本中显式调用将解决此问题.