2

I want to trap errors with my err function, which writes to the stderr. But in this example I am getting two error lines. How can I remove the first error msg not generated by my err function? I want to prevent something like

_get_error_msg 2> /dev/null 

or

exec 2> /dev/null

err() {
  echo -e "[$(date +'%H:%M:%S')] \e[31mERROR\e[0m $*" >&1
}

test.sh

#!/bin/bash

set -Eeo pipefail

err() {
  echo -e "[$(date +'%H:%M:%S')] \e[31mERROR\e[0m $*" >&2
}

trap 'err line "${LINENO}": "${BASH_COMMAND}"' ERR

_get_error_msg

I am getting this output:

./test.sh: line 11: _get_error_msg: command not found
[04:18:36] ERROR line 11: _get_error_msg

How can I remove

./test.sh: line 11: _get_error_msg: command not found

Or pipe this line also to my err() function to get something like this

[04:18:36] ERROR line 11: _get_error_msg: command not found

just one line written to the stderr?

EDIT: Something like this:

#!/bin/bash

set -Eeo pipefail

err() {
  echo -e "[$(date +'%H:%M:%S')] \e[31mERROR\e[0m $*"
}

err_msg() {
  while IFS= read -r msg; do
    err "${msg}"
  done
}

exec 2> >(err_msg)
trap 'err line "${LINENO}": "${BASH_COMMAND}"' ERR


_get_error_msg
mikee
  • 29
  • 3
  • So, you don't want bash's internal error messages to appear on the terminal? – oguz ismail Dec 07 '20 at 07:31
  • I want that any stderr output that occurs is written by my err function. So that every err gets formatted. Even the bash command not found error but also stderr msg generated by commands like cat -givemerror which also gives a error generated by cat. – mikee Dec 07 '20 at 11:42
  • 1
    Do : `{ _get_error_msg 2> /dev/null ;} 2>/dev/null`. `Something like this:` Is this the solution? Is your program solved? – KamilCuk Dec 07 '20 at 12:40
  • Using an ERR trap is probably not the way to do it. Instead, do something like `{ { echo stdout; echo stderr >&2; } 2>&1 >&3 | perl -pe 'print localtime . ": "'; } 3>&1`. It looks ugly in the comment but you can wrap your whole script, or use an auxiliary wrapper script. – William Pursell Dec 07 '20 at 12:51
  • 1
    In general, the issues caused by `set -e` far outweigh the minimal benefits. It's really not worth using. – William Pursell Dec 07 '20 at 12:52

0 Answers0