子脚本中的退出代码不正确

时间:2017-09-22 07:41:22

标签: linux bash exitstatus

我有一个父脚本,它在后台执行子脚本:

#!/bin/bash
# parent.sh
childScript $param1 $param2&

儿童剧本:

#!/bin/bash
# childScript.sh
param1=$1
param2=$2
someLinuxCommand $param1 $param2
out=$?
echo $out

如果我使用正确的$ param1和$ param2执行childScript.sh,$?将返回0.如果$ param1和$ param2不正确,$?将返回1.

但无论我使用parent.sh发送$ param1和$ param2,$?总是返回0.为什么我从parent.sh发送不正确的$ param1和$ param2,$?在childScript.sh中返回0?

1 个答案:

答案 0 :(得分:1)

在您的子脚本中,您“返回”echo的结果,该结果始终为0.您应该使用...

exit $? 

......相反。或者只是将这一行留在一起。

这是一个愚弄你的脚本的例子:

$ cat parent.sh
#!/bin/bash

p1=$1
p2='file'
./child.sh $p1 $p2

$ cat child.sh
#!/bin/sh

grep $1 $2
out=$?
echo $out

子脚本将“grep”为“文件”中的模式。以下是文件“file”的内容。

$ cat file
c.sh
file
in.txt
p.sh
bill

如果grep找到文件中的模式,grep会成功,因此设置$?到0.但是如果grep没有找到文件中的模式grep将失败此设置$?到1。

这里我们运行父模式为“bob”

$ ./parent.sh bob
1

grep未找到bob,因此将$?设置为1. echo输出1,然后将$?设置为0.

$ echo $?
0

让我们将child.sh脚本修复为:

$ cat child.sh
#!/bin/sh

grep $1 $2

再次运行parent.sh:

$ ./parent.sh bob
$ echo $?
1

$ ./parent.sh bill
bill
$ echo $?
0