Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to create some error reporting using a Trap to call a function on all errors:

Trap "_func" ERR

Is it possible to get what line the ERR signal was sent from? The shell is bash.

If I do that, I can read and report what command was used and log/perform some actions.

Or maybe I'm going at this all wrong?

I tested with the following:

#!/bin/bash
trap "ECHO $LINENO" ERR

echo hello | grep "asdf"

And $LINENO is returning 2. Not working.

share|improve this question
    
You can look at the bash debugger script bashdb. It seems that the first argument to trap can contain variables that are evaluated in the desired context. So trap 'echo $LINENO' ERR' should work. –  donothingsuccessfully May 29 '12 at 18:53
    
hmm just tried this with a bad echo | grep command and it returns the line of the Trap statement. But I'll take a look at bashdb –  Mechaflash May 29 '12 at 18:56
    
I'm so sorry... I didn't specify in my original question that I need a native solution. I edited the question. –  Mechaflash May 29 '12 at 19:05
    
Sorry, I borked the example line: trap 'echo $LINENO' ERR. The first argument to trap is the entire echo $LINENO hardquoted. This is in bash. –  donothingsuccessfully May 29 '12 at 19:43
4  
@Mechaflash It would have to be trap 'echo $LINENO' ERR, with single quotes, not double quotes. With the command you wrote, $LINENO is expanded when line 2 is parsed, so the trap is echo 2 (or rather ECHO 2, which would output bash: ECHO: command not found). –  Gilles May 29 '12 at 23:56

1 Answer 1

up vote 9 down vote accepted

As Gilles and donothingsuccessfully have pointed out in comments, your quoting is wrong. You need single quotes to prevent $LINENO from being expanded when the trap line is first parsed.

This works:

#! /bin/bash

err_report() {
    echo "Error on line $1"
}

trap 'err_report $LINENO' ERR

echo hello | grep foo
 $ ./test.sh
 Error on line 9
share|improve this answer
    
thanks for the example with a function call. I didn't know that double quotes expanded the variable in this case. –  Mechaflash May 30 '12 at 14:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.