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:

  1. trap exit signals should trigger onexit() function in code below
  2. 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:

  1. add set -o pipefail
  2. get exit status on onexit() adding local 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

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -