微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

发送stderr / stdout消息来运行和陷阱出口信号

我正在处理错误并logging在我的bash脚本。 下面我已经包含了一个简单的代码片段来举例说明用例。

我想在我的脚本中实现以下function:

陷阱应该在下面的代码中触发onexit()函数

应该将stderr和stdout发送到log()函数,这将确保根据特定的日志格式将输出logging到日志文件(在下面的示例中进行了简化)

用下面的当前代码问题:

第一步不会被onexit函数困住,脚本继续执行第2步。很可能是因为stderr被传送到了logStd()。 我怎么能发送错误消息到logStd(),但仍然陷阱退出信号onexit()?

parsing度:

shell脚本创buildlinux用户帐户,但密码出错

即使网站在线,Ping也会返回false

Apache访问日志中最常见的IP地址bash脚本

xpath html将所有列1和2连接在一起,并与列“:”

如何检查一个程序是否在Windows上的Ubuntu上运行,而不仅仅是简单的Ubuntu?

添加set -o pipefail

通过添加local exit_status=${1:-$?}获取onexit()的退出状态

script.sh(在parsing后编辑)

#!/bin/bash -E set -o pipefail # Perform program exit housekeeping function onexit { local exit_status=${1:-$?} log "onexit() called with param: $exit_status" exit $1 } # Simplified log function that sends input parameter to echo. This function is used within this script # In real case this function would send log statement to log file according to specific log format function log { echo "log(): $1" } # Simplified log function that reads input stream and sends to log # This function is used from commands function logStd { log "logStd() called" while IFS= read -r line; do log "$line"; done } # http://linuxcommand.org/wss0160.PHP # The trap command allows you to execute a command when a signal is received by your script. # Usage: trap arg signals # "signals" is a list of signals to intercept and "arg" is a command to execute when one of the signals is received # arg can either be a command or a function name like clean_up below trap onexit 1 2 3 15 ERR # STEP 1 - should fail,send errors to logstd() and be trapped by onexit() log "**Tarballing should fail,file doesn´t exist" tar -czf /Users/ismar.slomic/shellscripting/unkNownfile.txt.gz /Users/ismar.slomic/shellscripting/unkNownfile.txt 2>&1 | logStd # STEP 2 - should run successfully and send "tar: Removing leading '/' from member names" to logStd() log "**Tarballing should run successfully" tar -czf /Users/ismar.slomic/shellscripting/file.txt.gz /Users/ismar.slomic/shellscripting/file.txt 2>&1 | logStd onexit

输出

log(): **Tarballing should fail,file doesn´t exist log(): logStd() called log(): tar: /Users/ismar.slomic/shellscripting/unkNownfile.txt: Cannot stat: No such file or directory log(): tar: Error exit delayed from prevIoUs errors. log(): **Tarballing should run successfully log(): logStd() called log(): tar: Removing leading '/' from member names log(): onexit() called with param:

在服务中使用sudo启动CenstOS

tempfile和mktemp有什么区别?

如何从variables执行一个bash命令

将参数从调用bash脚本传递给Rscript

当在bash中的命令之间使用和号(&)时,redirectstdout和stderr

你必须使用

set -o pipefail

看到这个相关的StackOverflow问题 。

最小的例子

#!/bin/bash trap handler ERR handler() { echo trapped ; } echo 1 false | : echo 2 set -o pipefail false | :

输出

$ bash test.sh 1 2 trapped

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐