开发者

stop a calling script upon error

I have 2 shell scripts, namely script 开发者_JS百科A and script B. I have both of them "set -e", telling them to stop upon error.

However, when script A call script B, and script B had an error and stopped, script A didn't stop.

What can I stop the mother script when the child script dies?


It should work as you'd expect. For example:

In mother.sh:

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

In 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)"

Calling mother.sh:

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

Why is it not working for you?

One possible situation where it won't work as expected is if you specified -e in the shabang line (#!/bin/bash -e) and passed the script directly to bash which will treat that as a comment.

For example, if we change mother.sh to:

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

Notice how it behaves differently depending on how you call it:

[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)

Explicitly calling set -e within the script will solve this problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜