Bash Trap: how to get a subprocess line number with non-zero status

For the Bash program:

 1  #!/bin/bash
 2  
 3  trapinfo()
 4  {
 5     echo "=== Trap Info: Status=$? LINENO=$@ A=$A"
 6  }
 7  
 8  main()
 9  {
10     trap 'trapinfo $LINENO -- ${BASH_LINENO[*]}' ERR
11  
12     set -e
13     set -E
14     set -o errtrace
15     shopt -s extdebug
16  
17     local -g A=1
18  
19     # false        # If uncommented, LINENO would be 19
20     (exit 73)      # LINENO is 9. How can I get 20 instead?
21  
22     A=2
23  }
24  
25  main

with output:

=== Trap Info: Status=73 LINENO=9 -- 25 0 A=1

I am looking for a way to find it so that subshells that exit with non-zero status fall on trapand show the row number of the unsuccessful subshell. In the above example, I am looking for line 20 . I note that if the error is not in the subshell, I get the desired line number (see falseabove).

I tried moving the trap right in front of the subshell to check if the line number 9was actually associated with the trap call, but I get the same results. I also tried to put the record setand shoptto the subshell - again no change in behavior.

Environment:

  • bash -4.2.46-21.el7_3.x86_64: , POSIX . Bash (4.2 +).
  • CentOS 7 +:, CentOS, Bash, Ubuntu 16.04+ CentOS 6.

, ? , - ? , .

+4
2

Bash help- bash . , Bash, .

-, :

     1  #!/bin/bash
     2  shopt -s extdebug
     3  main() {
     4  trap 'echo $LINENO' ERR
     5  (exit 17)
     6  }
     7  main

3.

$(...) `...`:

     1  #!/bin/bash
     2  shopt -s extdebug
     3  main() {
     4  trap 'echo $LINENO' ERR
     5  `exit 17`
     6  }
     7  main

5.

:

     1  #!/bin/bash
     2  shopt -s extdebug
     3  main() {
     4  trap 'echo $LINENO' ERR
     5  $(exit 17)
     6  }
     7  main

5.

, , -, , Bash, ().

, . , , , ; .

0
#!/bin/bash

trapinfo()
{
   echo "=== Trap Info: Status=$? LINENO=$@ A=$A"
}

main()
{
   trap 'trapinfo $LINENO $SAVE_IT -- ${BASH_LINENO[*]}' ERR

   set -e
   set -E
   set -o errtrace
   shopt -s extdebug

   local -g A=1

   # false        # If uncommented, LINENO would be 19
   SAVE_IT=$LINENO && (exit 73)     # LINENO is magic, but a custom variable isn’t

   A=2
}

main

, - , , , ...

+1

Source: https://habr.com/ru/post/1665008/


All Articles