Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have several questions I want to understand in regards to error trap.

  1. why does the code below execute only 1 trap and not 2 and specifically only the code with "mydir2" and not "mydir1"?
  2. why at all is it executing the trap?
  3. why the command, if written as the marked code, will not generate a trap at all.
  4. what is the best / proper way to write this code.
  5. why and how do I get the correct line number for the error command and not the line of the function FuncA?

    #!/bin/bash
    
    set -o errtrace
    trap 'printerr' ERR
    function printerr(){
     local lc="$BASH_COMMAND" rc=$? ln=${BASH_LINENO[$i]}
     echo "$(date +%s) : Command [ $lc ] exited with code [ $rc ] in line [ $ln ]"
    }
    
    
    function FuncA(){
    
    [[ -d mydir1 ]] && echo mydir1OK
    
    [[ -d mydir2 ]] && echo mydir2OK
    
    #if [ -d /mtdir/ ] ;then
    #       echo OKMYDIR
    #fi
    
    }
    
    FuncA
    

Result:

1457453672 : Command [ [[ -d mydir2 ]] ] exited with code [ 1 ] in line [ 13 ]
share|improve this question

It seems the ERR trap is executed because the function FuncA has a non-zero exit status. As documented in man bash

the exit status of a function is the exit status of the last command executed in the body.

Which, in this case, was the [[ -d mydir2 ]]. You can add a true as the last command in the function to prevent it.

The if construct is different, because (same manual):

The exit status is the exit status of the last command executed, or zero if no condition tested true.

I'd recommend using if rather than adding a true.

share|improve this answer
    
The answer seems right, except it doesn't explain why $BASH_COMMAND contains [[ -d mydir2 ]] rather than FuncA. – Barmar Mar 8 at 20:15
    
@Barmar: Because [[ -d mydir2 ]] was the last executed command. – choroba Mar 8 at 20:58
    
But the manual says it should be the command that triggered the ERR trap, and that was FuncA. – Barmar Mar 8 at 21:02

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.