【发布时间】:2012-09-26 03:35:54
【问题描述】:
我一直在关注一些类似的问题(例如How to set a variable to the output from a command in Bash?),但是接受的答案似乎对我不起作用。我不确定我是否应该破坏别人的问题或发布我自己的副本,所以如果我在这里选错了,请道歉。
我希望在我正在整理的脚本中获得许多命令的输出和退出状态。这是我一直在使用的示例:
cmd_output=$(rm $file)
exit_status=$?
if [ "${exit_status}" -eq 0 ]
then
log "Successfully removed the original" ${TAB_LEVEL}
else
fail "Failed to remove the original, the output was: \n ${cmd_output}"
fi
日志和失败函数是:
# Usage: fail "Failure message"
function fail {
echo "FATAL ERROR: $1" >> "${LOG_DIR}/${LOG_FILE}"
exit 1
}
# Usage: log "Log message" 3 Where the tab-level is 3.
function log {
if (("${2}" > 0))
then
eval "printf ' %.0s' {1..$2}" >> "${LOG_DIR}/${LOG_FILE}"
fi
echo "$1" >> "${LOG_DIR}/${LOG_FILE}"
return 0
}
在上面的示例中,我使用了 $(cmd) 格式,但我也尝试过使用反引号。
在我的日志文件中,出现故障时我看到的是:
致命错误:无法删除原件,输出为:\n
此外,失败命令的输出会照常显示在屏幕上。我的 cmd_output 变量保持为空的常见原因是什么?
【问题讨论】:
标签: bash shell ubuntu command-line