我使用以下选项
set -o pipefail
set -e
在bash脚本中停止执行错误。我有~100行脚本正在执行,我不想检查脚本中每一行的返回代码。
但是对于一个特定的命令,我想忽略这个错误。我该怎么做呢?
我使用以下选项
set -o pipefail
set -e
在bash脚本中停止执行错误。我有~100行脚本正在执行,我不想检查脚本中每一行的返回代码。
但是对于一个特定的命令,我想忽略这个错误。我该怎么做呢?
当前回答
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
不要停止,也保存退出状态
以防万一,如果你想让你的脚本不停止,如果一个特定的命令失败,你也想保存失败命令的错误代码:
set -e
EXIT_CODE=0
command || EXIT_CODE=$?
echo $EXIT_CODE
虽然|| true是首选之一,但你也可以这样做
var=$(echo $(exit 1)) # it shouldn't fail
感谢上面的简单解决方案:
<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”,您还可以使用“noop”或null实用程序(在POSIX规范中提到):并且只是“什么都不做”。你可以省下几个字母。:)
#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."