본문 바로가기
프로그래밍/Linux

[Linux] 쉘 스크립트(Shell script) 4편 - 디버그 모드, 에러메시지 출력

by HI_Ai 2023. 8. 31.
반응형

1. 디버그 모드 (-x 옵션) 사용하기

쉘 스크립트 디버깅은 스크립트가 예상대로 동작하지 않을 때 문제의 원인을 찾아 수정하는 과정입니다. 쉘 스크립트 디버깅은 다른 프로그래밍 언어에서의 디버깅과는 약간 다르게 진행될 수 있습니다. 여기에는 쉘 스크립트 디버깅에 사용되는 몇 가지 기본적인 기술들을 나열해보겠습니다:

 

방법 1: 스크립트 실행 시 -x 옵션 사용

스크립트(sample_script.sh)를 작성하겠습니다.

#!/bin/bash

echo "Starting the script..."
MY_VARIABLE="Hello, World"
echo $MY_VARIABLE

이후 아래 코드를 작성하면 디버깅한 결과가 모두 출력됩니다.

bash -x yourscript.sh


+ echo 'Starting the script...'
Starting the script...
+ MY_VARIABLE='Hello, World'
+ echo 'Hello, World'
Hello, World

 

방법 2: 스크립트 내에서 set -x 및 set +x 사용

스크립트 (sample_script.sh)를 먼저 작성하겠습니다.

#!/bin/bash

echo "Before debug mode..."

set -x  # 디버그 모드 시작
echo "This will be printed in debug mode."
MY_VAR="Debugging"
echo $MY_VAR
set +x  # 디버그 모드 종료

echo "After debug mode..."

sample_script.sh 저장 이후 아래와 같이 bash 명령어에 작성하면 다음과 같이 실행됩니다.

$ ./sample_script.sh


Before debug mode...
+ echo 'This will be printed in debug mode.'
This will be printed in debug mode.
+ MY_VAR=Debugging
+ echo Debugging
Debugging
+ set +x
After debug mode...

여기서 + 기호는 디버그 모드에서 각 명령어의 실행을 나타냅니다. 이를 통해 스크립트의 어떤 부분이 실행되는지, 어떤 명령어가 어떤 출력을 생성하는지 알 수 있습니다.

 


에러 메시지 출력하기

에러 메시지 출력을 위해 쉘 스크립트에서는 주로 stderr를 이용합니다. 기본적으로, 쉘에서는 두 개의 출력 스트림, stdout(표준 출력)와 stderr(표준 에러)이 있습니다. 에러 메시지를 표준 에러로 출력하려면 다음과 같이 사용할 수 있습니다.

 

먼저 예시를 위해 error_handling_script.sh를 만들겠습니다.

#!/bin/bash

# A function to simulate an error
function cause_error {
  echo "This is an error message." >&2
}

echo "This script will cause an error..."
cause_error
echo "The script continues after the error..."

이후 아래와 같이 실행을 하면 됩니다.

$ chmod +x error_handling_script.sh
$ ./error_handling_script.sh

This script will cause an error...
This is an error message.
The script continues after the error...

위와 같이 실행하면 모든 출력이 함께 표시됩니다.

만약에 에러 메시지만 별도로 보고 싶다면, stderr를 다른 곳으로 리다이렉트 할 수 있습니다:

$ ./error_handling_script.sh 2> error.log


이렇게 하면, "This is an error message."라는 메시지가 error.log라는 파일에 저장되고, 터미널에는 그 외의 메시지만 출력됩니다. error.log 파일을 열어보면 에러 메시지를 확인할 수 있습니다.

반응형