ERR을 발생시킨 전체 명령줄을 가져오는 동안 트랩을 수행합니다.

ERR을 발생시킨 전체 명령줄을 가져오는 동안 트랩을 수행합니다.

ERR을 발생시킨 명령을 반환하는 트랩을 어떻게 만드나요?

$function err_handler() { echo "$0 caused the error"; }

$ trap err_handler ERR

$ grep -ci "failed" test4 &>/dev/null
-bash caused the error

나는 다음과 같은 출력을 원했습니다.

grep caused the error

그리고 전체 명령줄을 대체할 수 있을 만큼 탐욕스러울 수도 있습니다. (해킹 없이) 가능합니까?

편집: 내 쉘이 KSH라는 사실을 언급하지 않은 것에 대해 사과드립니다.

답변1

명령 기록이 활성화되어 있는지 확인하고(비대화형 쉘의 경우 기본적으로 꺼져 있음) 다음을 사용하십시오.

#!/bin/bash
set -o history
function trapper () {
    printf "culprit: "
    history 1
}

trap trapper ERR

# your errors go here

답변2

Bash를 사용하는 경우 다음 매개변수를 사용할 수 있습니다 $BASH_COMMAND.

BASH_COMMAND
    The command currently being executed or about to be executed, unless
    the shell is executing a command as the result of a trap, in which case
    it is the command executing at the time of the trap.

몇 가지 참고 사항: 첫 번째는 $BASH_COMMAND전체 명령줄이 아닌 복합 명령에서 실패한 명령만 제공합니다.

$ function err_handler { echo "error: $BASH_COMMAND" }
$ trap err_handler ERR
$ true blah blah blah && false herp derp
error: false herp derp

둘째, 파이프라인은 마지막 명령이 실패하는 경우에만 실패합니다. 중간 명령이 실패하더라도 마지막 명령은 성공하더라도 여전히 성공합니다.

$ echo okay | false herp derp | true lol
# err_handler not called, the last command returned true.

셋째, $BASH_COMMAND당신에게 다음을 제공합니다구문 분석되지 않은따라서 명령줄의 첫 번째 항목은 특수한 상황에서 반드시 명령 이름일 필요는 없습니다.

$ false herp derp                       # This is okay.
error: false herp derp
$ {false,herp,derp}                     # An obfuscated way to write `false blah blah`
error: {false,herp,derp}
$ cmd=false
$ $cmd herp derp                        
error: $cmd herp derp

관련 정보