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.
'Engineering > ShellScript' 카테고리의 다른 글
텍스트 파일에서 특정 문자열들이 몇번이나 나왔는지를 알아보는 스크립트 (0) | 2017.07.27 |
---|---|
CentOS 버전에 따라서 다른 작업을 하는 shell 스크립트 (0) | 2014.08.12 |