3

test.sh

#!/bin/bash
set -e
trap 'echo $LINENO' EXIT
/bin/false

run

$ ./test.sh
1

How may I get the actual line number of "/bin/false" instead of always '1'?

Darren Ng
  • 373
  • 5
  • 12
  • 1
    what do you mean with `the actual number of "/bin/false"`? you get `1` which is the result of `echo $LINENO` invoked at `EXIT` – MarcoLucidi Aug 25 '20 at 13:39
  • 2
    Can't reproduce, if I run your `test.sh` on my machine, it shows `4` *as expected*. – 0stone0 Aug 25 '20 at 13:41
  • [He said he got 12 but we all fail.](https://medium.com/@dirk.avery/the-bash-trap-trap-ce6083f36700) – Darren Ng Aug 26 '20 at 02:03
  • I can reproduce the same behavior and landed here looking for the same problem. – lud Aug 27 '20 at 09:38

1 Answers1

5

You are getting 1 because you trap EXIT. Try :

trap ... ERR
Philippe
  • 20,025
  • 2
  • 23
  • 32
  • What if I wanted to get the line number of an EXIT signal without error? Is that possible? I see the same, $LINENO always 1 when trap ... EXIT is called, but the same works with trap .. ERR. However I want to have a generic trap that captures both normal and error exit and handles errors in the trap function. – lud Aug 27 '20 at 09:33
  • 1
    @lud, unfortunately, bash reset LINENO before calling trap for EXIT. – Philippe Sep 01 '20 at 19:52
  • This is not true for all Bash versions. Bash 3 (specifically Bash 3 on macOS) will report the lineno on trap exit (if there was an error and assuming set -o errexit). – Mangled Deutz Aug 02 '22 at 22:35
  • Meaning: although the question is closed and could be expressed otherwise, the desired behavior of OP is working as-is in bash 3. In other bash versions, you can trap both ERR and EXIT, and store the lineno in a variable on ERR - output the value of that variable in EXIT if defined. – Mangled Deutz Aug 02 '22 at 22:41