backend/ubuntu

linux command line - 30. troubleshooting

seul chan 2021. 6. 6. 20:36

30. Troubleshooting

스크립트가 복잡해질수록 문제가 발생할 가능성이 많아짐.

여기에서는 스크립트에서 발생하는 일반적인 몇가지 오류를 살펴보고 문제를 추적/근절하는 몇가지 기술 소개

#!/bin/bash

# trouble: script to demonstrate common errors

number=1

if [ $number = 1 ]; then
      echo "Number is equal to 1."
else
      echo "Number is not equal to 1."
fi

Syntax error

가장 흔하게 발생하는 에러. 쉘은 syntax error가 발생하면 스크립트 실행을 중지시킴.

Missing quote

quoting이 없으면 에러가 나는 경우. 에러 메세지의 줄 번호가 누락된 따옴표가 있는 곳이 아니라 프로그램의 후반부이기 때문에 스크립트에서 이런 오류를 찾기가 어려울 수 있음.

vim이나 다른 syntax highlighting을 제공하는 에디터를 사용하는게 도움이 됨.

#!/bin/bash

# trouble: script to demonstrate common errors

number=1

if [ $number = 1 ]; then
      echo "Number is equal to 1.
else
      echo "Number is not equal to 1."
fi

Missing or unexpected tokens

if나 while 등의 compound command를 끝마치는것을 안하는 경우. semicolon이 없는 경우에도 마찬가지.

#!/bin/bash

# trouble: script to demonstrate common errors

number=1

if [ $number = 1 ] then
      echo "Number is equal to 1."
else
      echo "Number is not equal to 1."
fi

이 경우에도 에러 메세지는 해당 줄이 아니라 이후의 줄을 가리킨다.

[me@linuxbox ~]$ trouble
/home/me/bin/trouble: line 9: syntax error near unexpected token `else'
/home/me/bin/trouble: line 9: `else'

Unanticipated Expansions

값에 따라서 어떤 경우에는 잘 작동하고 어떤 경우에는 작동하지 않을 수 있음.

#!/bin/bash

# trouble: script to demonstrate common errors

number=

if [ $number = 1 ]; then
      echo "Number is equal to 1."
else
      echo "Number is not equal to 1."
fi

number 값이 없기 때문에 [ = 1 ]이라는 애매한 식이 생겨서 에러가 남.

[me@linuxbox ~]$ trouble
/home/me/bin/trouble: line 7: [: =: unary operator expected
Number is not equal to 1.

이런 경우 $number 인수에 따옴표를 추가하여 수정할 수 있다.

["$number"=1]

이 경우 expansion이 발생하면 아래와 같이 되기 때문에 올바른 인수가 산출된다.

[""=1]

Logical errors

syntax error와 다르게 logical error는 스크립트의 작동을 멈추지는 않는다.

하지만 이는 로직에 문제가 있기 때문에 원하는 결과를 반환하지 않게 됨.

  • incorrect conditional expressions
  • "Off by one" errors
  • Unanticipated situations