chkconfig --list | grep --quiet"码头"不会在shell脚本中工作

时间:2015-01-23 04:23:19

标签: bash shell

chkconfig --list | grep --quiet"码头"在没有" set -o pipefail"的情况下在命令行或脚本中工作,不能使用" set -o pipefail"在脚本中。为什么呢?

原始剧本:

#!/usr/bin/env bash
set -e
set -o pipefail

echo -e "checking jetty is installed ...\n"
echo -e "start...\n"
chkconfig --list | grep --quiet "jetty"
echo $?
echo -e "end...\n"
if [ $? -eq 0 ]; then
    echo "ok"
else
    echo "fail"
fi
跟踪执行后

: 它输出"开始...",运行" chkconfig --list |后脚本退出grep --quiet jetty",so" echo $?"后者跟踪输出没什么。只是不知道管道失败的原因。如果我评论"设置-o pipefail",那么脚本工作正常。

环境:

1)CentOS版本6.6(最终版)64位

2)GNU bash,版本4.1.2(1)-release(x86_64-redhat-linux-gnu)

3)GNU grep 2.6.3

2 个答案:

答案 0 :(得分:0)

使用set -e,如果grep找不到匹配项,那么该脚本将退出 - 这是set -e所做的事情,它会将每个错误转换为致命错误一。您需要在错误处理条件中包装任何可能失败的命令。幸运的是,即使没有set -e,也应该如何编写这个特定的脚本。

if chkconfig --list | grep --quiet 'jetty'; then
    echo "ok"
else
    echo "fail"
fi

答案 1 :(得分:-1)

您不应该使用set -e,因为如果遇到任何错误命令,它将让脚本退出。 此外echo $?之后的chkconfig --list | grep --quiet "jetty"似乎已经改变了你的“$?”值。

所以你可以这样写:

if chkconfig --list | grep --quiet "ssh"
then
    echo "ok"
else
    echo "fail"
fi