我使用以下选项

set -o pipefail
set -e

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

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


当前回答

除了“返回true”,您还可以使用“noop”或null实用程序(在POSIX规范中提到):并且只是“什么都不做”。你可以省下几个字母。:)

#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."

其他回答

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

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

如果你想防止你的脚本失败并收集返回代码:

command () {
    return 1  # or 0 for success
}

set -e

command && returncode=$? || returncode=$?
echo $returncode

无论命令成功还是失败,都会收集Returncode。

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

<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。

我有点喜欢这个解决方案:

: `particular_script`

在反勾号之间执行命令/脚本,并将其输出提供给命令":"(相当于"true")。

$ false
$ echo $?
1
$ : `false`
$ echo $?
0

编辑:修正了丑陋的错别字