2014-12-09 12 views
7

Quando si utilizza il chiamante incorporato in una funzione Bash trap, il risultato di caller 0 fornisce il numero di riga errato, dando sempre 1. Ad esempio:Il chiamante 0 fornisce il numero di riga errato nel gestore trap

#!/bin/bash 
function foo { 
    exit 1 
} 
function bar { 
    foo 
} 
function err { 
    ((i = 0)) 
    while caller $i; do 
     ((++i)) 
    done 
} 
trap err EXIT 
bar 

pronunciato la seguente output:

1 foo ./test.sh 
6 bar ./test.sh 
15 main ./test.sh 

Mentre l'output per i > 0 è corretta, quando si utilizza caller 0 in un gestore trappola sembra sempre dare 1 come il numero di riga. C'è un modo per ottenere il numero di linea reale della funzione fallita da un gestore trap?

+0

L'array 'BASH_LINENO' è tuo amico. (Quindi sono 'FUNCNAME' e' BASH_SOURCE'). –

+0

@CharlesDuffy Sfortunatamente 'BASH_LINENO' dà semplicemente la stessa cosa di' caller 0': '1' – Xenopathic

+0

... e quindi' trap'e err "$ LINENO" '', per quella questione. Francamente, non ho mai visto le trappole EXIT utilizzate in questo modo - probabilmente stai colpendo comportamenti che nessuno si è mai preso la briga di testare. Usare una trappola ERR sarebbe molto meno insolito. –

risposta

3

questo sembra essere un bug introdotto qualche tempo dopo 3.2.57 (1) -RELEASE:

$ bash -version 
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14) 
Copyright (C) 2007 Free Software Foundation, Inc. 

$ bash ./test.sh 
3 foo ./test.sh 
6 bar ./test.sh 
15 main ./test.sh 

$ /usr/local/bin/bash --version 
GNU bash, version 4.3.30(1)-release (x86_64-apple-darwin14.1.0) 
Copyright (C) 2013 Free Software Foundation, Inc. 
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> 

This is free software; you are free to change and redistribute it. 
There is NO WARRANTY, to the extent permitted by law. 

$ /usr/local/bin/bash ./test.sh 
1 foo ./test.sh 
6 bar ./test.sh 
15 main ./test.sh 

Sembra che ci sia già un bug report con il progetto bash.

+0

Di recente ci cadiamo dentro. Sono contento di sapere perché ... –

+0

I [bug nelle trappole ERR e RETURN sono ora riparati] (http://lists.gnu.org/archive/html/bug-bash/2015-02/msg00132.html) – Manubhargav

+0

Questo sembra essere stato risolto, almeno nei miei test. –

Problemi correlati