我使用以下选项

set -o pipefail
set -e

在bash脚本中停止执行错误。我有~100行脚本正在执行,我不想检查脚本中每一行的返回代码。

但是对于一个特定的命令,我想忽略这个错误。我该怎么做呢?


当前回答

只需在希望忽略错误的命令后添加|| true。

其他回答

解决方案:

particular_script || true

例子:

$ cat /tmp/1.sh
particular_script()
{
    false
}

set -e

echo one
particular_script || true
echo two
particular_script
echo three

$ bash /tmp/1.sh
one
two

第三部永远不会印刷。

另外,我想补充一点,当pipefail打开时, shell认为整个管道具有非零退出代码就足够了 当管道中的某个命令具有非零退出码(pipefail关闭时,它必须是最后一个)。

$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0

感谢上面的简单解决方案:

<particular_script/command> || true

以下结构可用于脚本步骤的其他操作/故障排除和其他流控制选项:

if <particular_script/command>
then
   echo "<particular_script/command> is fine!"
else
   echo "<particular_script/command> failed!"
   #exit 1
fi

如果需要,我们可以停止进一步的操作并退出1。

只需在希望忽略错误的命令后添加|| true。

output=$(*command* 2>&1) && exit_status=$? || exit_status=$?
echo $output
echo $exit_status

使用此命令创建日志文件的示例

log_event(){
timestamp=$(date '+%D %T') #mm/dd/yy HH:MM:SS
echo -e "($timestamp) $event" >> "$log_file"
}

output=$(*command* 2>&1) && exit_status=$? || exit_status=$?

if [ "$exit_status" = 0 ]
    then
        event="$output"
        log_event
    else
        event="ERROR $output"
        log_event
fi

在使用CLI工具时,我一直在使用下面的代码片段,我想知道是否存在一些资源,但我不关心输出。

if [ -z "$(cat no_exist 2>&1 >/dev/null)" ]; then
    echo "none exist actually exist!"
fi