bash - Send stderr/stdout messages to function and trap exit signal -
im working on error handling , logging in bash script. below have included simplified code snippet exemplify use case.
i want achieve following in script:
- trap exit signals should trigger onexit() function in code below
- stderr , stdout should sent log() function make sure log output log file according specific log format (simplified in example below)
issue current code below:
- step 1 not trapped onexit function , script continuing step 2. because stderr piped logstd(). how can send error messages logstd() still trap exit signal in onexit()?
resolution:
- add
set -o pipefail
- get exit status on
onexit()
addinglocal exit_status=${1:-$?}
script.sh (edited after resolution)
#!/bin/bash -e set -o pipefail # perform program exit housekeeping function onexit { local exit_status=${1:-$?} log "onexit() called param: $exit_status" exit $1 } # simplified log function sends input parameter echo. function used within script # in real case function send log statement log file according specific log format function log { echo "log(): $1" } # simplified log function reads input stream , sends log # function used commands function logstd { log "logstd() called" while ifs= read -r line; log "$line"; done } # http://linuxcommand.org/wss0160.php # trap command allows execute command when signal received script. # usage: trap arg signals # "signals" list of signals intercept , "arg" command execute when 1 of signals received # arg can either command or function name clean_up below trap onexit 1 2 3 15 err # step 1 - should fail, send errors logstd() , trapped 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 , send "tar: removing leading '/' member names" 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
output:
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 previous errors. log(): **tarballing should run log(): logstd() called log(): tar: removing leading '/' member names log(): onexit() called param:
you have use
set -o pipefail
see related stackoverflow question.
minimal example:
#!/bin/bash trap handler err handler() { echo trapped ; } echo 1 false | : echo 2 set -o pipefail false | :
output:
$ bash test.sh 1 2 trapped
Comments
Post a Comment