쉘스크립트

bash 사용 예

고요한하늘... 2011. 7. 19. 13:01

-------------------------------------------------------------------------

초기화 하지 않은 변수를 사용할때 리포팅

set -o nounset

-------------------------------------------------------------------------


-------------------------------------------------------------------------

쉘스크립트 중간에 에러가 발생했을때 즉시 스크립트를 정지한다.

set -o errexit

-------------------------------------------------------------------------



-------------------------------------------------------------------------

trap : signal을 잡을때 사용

trap "실행할 문자열, 함수명일때는 함수가 호출된다"  [catch할 signal]


catch할 signal을

trap -l 명령어로 확인할수 있다.( trap -l에 보여지는것 외에 DEBUG, RETURN, EXIT, ERR 사용가능 )

trap "error_handler" ERR

-------------------------------------------------------------------------


-------------------------------------------------------------------------

c언어에서 사용하는 const와 비슷한 명령어

readonly


readonly  readonly_var="foo";

-------------------------------------------------------------------------



-------------------------------------------------------------------------

function error_handler()
{
  STATUS=${1:-1}
  .....
}
${1:-1} <--- 이것은 $1에 대한 설정이다. 즉 error_handler()의 첫번째 파라미터에 대한 것으로

:- 라는 연산자 뒤에 오는 값을 초기값으로 사용할것을 지정한다.

즉 $1로 아무런 값이 넘어 오지 않으면 STATUS에 초기값으로 1을 세팅한다.


-------------------------------------------------------------------------




참고 : http://stackoverflow.com/questions/78497/design-patterns-or-best-practices-for-shell-scripts



#!/bin/bash


set -x

type11()

{

    local v=${1-"Default"};

    echo $v;

}


type12()

{

    local v=${1:-"Default"};

    echo $v;

}


type21()

{

    local v=${1="Default"};

    echo $v;

}


type22()

{

    v=${1:="Default"};

    echo $v;

}


type31()

{

    local v=${1+"Default"};

    echo $v;

}



type32()

{

    local v=${1+="Default"};

    echo $v;

}



type41()

{

    local v=${1?"Default"};

    echo $v;

}



type42()

{

    local v=${1:?"Default"};

    echo $v;

}

echo "-";
type11
type11 ""
type11 "message1"


type12
type12 ""
type12 "message2"


echo "=";
type21
type21 ""
type21 "message3"


type22
type22 ""
type22 "message4"


echo "+";
type31
type31 ""
type31 "message5"

type32
type32 ""
type32 "message6"

echo "?";
type41
type41 ""
type41 "message7"

type42
type42 ""
type42 "message8"


############################# 출력 ############################# 
-
Default

message1
Default
Default
message2
=
./test.sh: line 17: $1: cannot assign in this way

message3
./test.sh: line 23: $1: cannot assign in this way
./test.sh: line 23: $1: cannot assign in this way
message4
+

Default
Default

=Default
=Default
?
./test.sh: line 43: 1: Default

http://tldp.org/LDP/abs/html/refcards.html

'쉘스크립트' 카테고리의 다른 글

awk gsub  (0) 2012.02.29
parallel 병렬처리 명령어  (0) 2011.10.20
스크립트 실행 위치   (0) 2011.06.24
파일내부 vim설정  (0) 2010.12.28
쉘스크립트(bash) 디렉토리 & 경로명   (0) 2010.07.13