본문 바로가기

TroubleShooting/ShellScript

bash 스크립트 정리

728x90

bash 스크립트 작성할때 많이 사용하지만, 오랜만에 사용하면 헷갈리는 분기문들


1. 문자열 비교

#! /bin/bash

DB_TYPE=mysql


if [ "$DB_TYPE" == "postgresql" ]; then

    echo "postgresql"

elif [ "$DB_TYPE" == "mysql" ]; then

    echo "mysql"

else

    echo "none"

fi

※ if, elif 조건문의 "[", "]" 다음에 반드시 space(빈 공간이)이 있어야 한다.


2. 옵션값 체크

- 실행 스크립트의 옵션값에 따라서 다른 동작을 하기를 원할때 사용.

#! /bin/bash


alpha_flag=0

bravo_flag=0

charlie_flag=0


for arg

do

  case $arg in

    alpha) alpha_flag=1;;

    bravo) bravo_flag=1;;

    charlie) charlie_flag=1;;

    *) echo "Usage: `basename $0` [alpha] [bravo] [charlie]"

      exit 1;;

  esac

done


if [ $alpha_flag = 0 ] && [ $bravo_flag = 0 ] && [ $charlie_flag = 0 ] ; then

  alpha_flag=1

  bravo_flag=1

  charlie_flag=1

fi


if [ $alpha_flag = 1 ] ; then

  echo "alpha";

fi

if [ $bravo_flag = 1 ] ; then

  echo "bravo";

fi

if [ $charlie_flag = 1 ] ; then

  echo "charlie";

fi


실행 결과

[root@bigfoot tmp]# ./a.sh

alpha

bravo

charlie

[root@bigfoot tmp]# ./a.sh alpha

alpha

[root@bigfoot tmp]# ./a.sh bravo

bravo

[root@bigfoot tmp]# ./a.sh alpha charlie

alpha

charlie

[root@bigfoot tmp]# ./a.sh aa bb

Usage: a.sh [alpha] [bravo] [charlie]


3. 디렉토리가 존재하는 지 확인

#! /bin/bash


if [ ! -d ./testDir ]; then

  echo "Direcoty is not Found!!!";

else

  echo "Exist";

fi

※ -d : 디렉토리이면 true 값, -f : 파일이면 true 값, ! :  뒤에 조건이 false 일때만 true.