title: Bash: How to get the call chain on errors?
body: <p>I have a back trace function in bash that works well enough (code below) but the problem is that bash itself when it hits an error, it doesn't give a back trace or any kind of info that would help determine the caller, which can help in debugging the issue.</p>
  
  <p>e.g.:</p>
  
  <blockquote>
    <p>./c.sh: line 23: urgh: command not found</p>
  </blockquote>
  
  <pre><code>function backtrace () {
      local deptn=${#FUNCNAME[@]}
  
      for ((i=1; i&lt;$deptn; i++)); do
          local func="${FUNCNAME[$i]}"
          local line="${BASH_LINENO[$((i-1))]}"
          local src="${BASH_SOURCE[$((i-1))]}"
          printf '%*s' $i '' # indent
          echo "at: $func(), $src, line $line"
      done
  }
  </code></pre>
  
  <p>Is it possible to trap bash on such errors so I could call my own function to get output like this?</p>
  
  <pre><code> at: c(), ./c.sh, line 22
    at: b(), ./c.sh, line 11
     at: main(), ./b.sh, line 5
  </code></pre>
  
  <p>Update: final working version from suggestions and traceback trap on error:</p>
  
  <pre><code>function backtrace () {
      local deptn=${#FUNCNAME[@]}
  
      for ((i=1; i&lt;$deptn; i++)); do
          local func="${FUNCNAME[$i]}"
          local line="${BASH_LINENO[$((i-1))]}"
          local src="${BASH_SOURCE[$((i-1))]}"
          printf '%*s' $i '' # indent
          echo "at: $func(), $src, line $line"
      done
  }
  
  function trace_top_caller () {
      local func="${FUNCNAME[1]}"
      local line="${BASH_LINENO[0]}"
      local src="${BASH_SOURCE[0]}"
      echo "  called from: $func(), $src, line $line"
  }
  
  set -o errtrace
  trap 'trace_top_caller' ERR
  </code></pre>