gpt4 book ai didi

linux - 如果 [ $? -ne 0 ];不工作?

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:52 25 4
gpt4 key购买 nike

我正在尝试检测正在运行的服务,如果不存在,请尝试做一些事情:

#!/bin/bash

service --status-all | grep 'My Service' &> /dev/null

if [ $? -ne 0 ]; then
echo "Service not there."
else
echo "Service is there."
fi

服务显然存在,但我仍然得到“服务不存在”。

我读到了退出代码 $?我想也许一系列命令中的退出代码可能会影响我们想要测试的内容?

所以我不确定哪里出了问题?

最佳答案

要调试测试中发生的情况,请一次运行一个步骤。

首先自己执行 service --status-all 并检查其输出。输出是否符合您的预期,它是否真的包含您正在搜索的“我的服务”?

然后运行 ​​service --status-all | grep 'My Service' 并检查其输出和退出代码。它是否写出匹配项,退出代码是否为零 0

man grep 告诉我们:

The grep utility exits with one of the following values:

0 One or more lines were selected.
1 No lines were selected.
>1 An error occurred.

还有

-q, --quiet, --silent
Quiet mode: suppress normal output. grep will only search a file until a
match has been found, making searches potentially less expensive.

您还可以对这个过程进行改进...

if 测试执行的命令列表的返回状态,如果该状态为零,则执行 then 分支。了解这一点后,您可以只测试 grep 的返回状态,而不是 test 的返回状态。


旁白:
您正在使用 [ 命令,它也是 test 命令(尝试 man test)
test 命令在测试通过(成功)时以 0 退出,或者在测试失败时以 1 退出。

$ test 7 -eq 7;echo $?
0
$ test 7 -ne 7;echo $?
1
$ [ 7 -eq 2 ];echo $?
1

有了这些知识,再一次,你可以直接测试grep的退出代码。
使用“quiet”标志而不是重定向来抑制 grep 的输出,并对固定字符串使用 grep -F,也就是 fgrep:

if ./service --status-all | fgrep -q 'My Servvice'
then
echo "Service IS there."
else
echo "Service NOT there."
fi

关于linux - 如果 [ $? -ne 0 ];不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40010332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com