if 문을 사용하여 종료 상태를 확인하는 방법
특정 출력을 에코하기 위해 if 문에서 종료 상태를 확인하는 가장 좋은 방법이 무엇인지 궁금합니다.
나는 그것이 생각
if [ $? -eq 1 ]
then
echo "blah blah blah"
fi
내가 가지고있는 문제는 종료 문이 if 문 앞에 있다는 것입니다. 종료 코드가 있어야하기 때문입니다. 또한 종료는 분명히 프로그램을 종료하기 때문에 내가 잘못하고 있다는 것을 알고 있습니다.
실행되는 모든 명령에는 종료 상태가 있습니다.
이 검사는 해당 행이 실행되기 전에 가장 최근에 완료된 명령의 종료 상태를보고 있습니다.
당신이 원하는 경우에 당신의 그 평가 결과가 true 때 종료에 스크립트를 다음 넣어 (이전 명령이 실패) exit 1
그 내부 (또는 무엇이든) if
애프터 블록 echo
.
명령을 실행 중이고 다음을 사용하여 출력을 테스트하려는 경우 종종 더 간단합니다.
if some_command; then
echo command returned true
else
echo command returned some error
fi
또는 !
부정을 위해 사용을 돌리기 위해
if ! some_command; then
echo command returned some error
else
echo command returned true
fi
그 중 어느 것도 오류 코드가 무엇인지 신경 쓰지 않습니다 . 특정 오류 코드에만 관심이있는 경우 $?
수동으로 확인 해야합니다.
종료 코드! = 0은 오류를보고하는 데 사용됩니다. 따라서 수행하는 것이 좋습니다.
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Error"
fi
exit $retVal
대신에
# will fail for error codes > 1
retVal=$?
if [ $retVal -eq 1 ]; then
echo "Error"
fi
exit $retVal
$?
다른 매개 변수와 같습니다. 최종적으로 호출하기 전에 사용할 값을 저장할 수 있습니다 exit
.
exit_status=$?
if [ $exit_status -eq 1 ]; then
echo "blah blah blah"
fi
exit $exit_status
명시 적 if
진술의 대안
최소한 :
test $? -ne 0 || echo "something bad happened"
완전한:
EXITCODE=$?
test $EXITCODE -ne 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE
도움이되고 자세한 답변 을 추가하려면 다음을 수행하십시오 .
If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... ))
, this way:
run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }
Or, use a case
statement:
run_some_command; ec=$? # grab the exit code into a variable so that it can
# be reused later, without the fear of being overwritten
case $ec in
0) ;;
1) printf '%s\n' "Command exited with non-zero"; exit 1;;
*) do_something_else;;
esac
Related answer about error handling in Bash:
The answer by Oo.oO is correct.
If you want to go one step further, I use this in my PS1 in order to view the exit code of every command only if it's error:
function ret_validate { if [ $1 != 0 ] ; then echo -n -e " Err:$1" ; fi }
PS1='${debian_chroot:+($debian_chroot)}[\t]\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\e[01;31m\]`ret_validate \$?`\[\e[m\] \$ '
Just add those lines to your .bashrc
if you want to see it.
참고URL : https://stackoverflow.com/questions/26675681/how-to-check-the-exit-status-using-an-if-statement
'Programing' 카테고리의 다른 글
배열의 첫 번째 N 요소를 얻습니까? (0) | 2020.05.15 |
---|---|
Python Pandas 명시 적으로 열을 나열하지 않고 DataFrame에서 하나 이상의 null이있는 행을 선택하는 방법은 무엇입니까? (0) | 2020.05.15 |
UIImage : 크기 조정 후 자르기 (0) | 2020.05.15 |
IntelliJ IDEA 기본 JDK를 어떻게 변경합니까? (0) | 2020.05.15 |
Gulp를 사용한 Concat 스크립트 (0) | 2020.05.15 |