TODAY 105
Bash Script Tip

(1) 첫줄은 env로 사용할것

#!/usr/bin/env bash 


(2) .properties 파일을 사용할것
하나의 스크립트를 여러 경로 혹은 여러 서버에서 실행할시 프로퍼티를 만들어서 주요 변수들은 특정 파일로 뺴는것이 좋다.

(2-1) properties 파일 생성
cat test.properties

app.check=properties 
app.exc.path=/home/cron/ 
app.csv.path=/home/cron/csv/ 
app.log.path=/home/cron/log/ 


(2-2) 실제 sh 파일 생성
cat test.sh

#!/usr/bin/env bash 
SCRIPTPATH=$( cd "$(dirname "$0")" ; pwd -P ) 
if [ -z "$1" ]; then echo "[ERROR]Parameter required."; exit 1; fi 
ENV=${1}; 
function prop { grep "${1}" ${SCRIPTPATH}/${ENV}.properties|cut -d'=' -f2; } 
if [ -z "$(prop 'app.check')" ]; then exit 1; fi

이후 스크립트 파일을 실행할시에 sh '스크립트 파일명' 매개변수 이런식으로 실행이 가능하다.
-> $(prop 'KEY 이름')  으로 값을 호출할수 있습니다.

(3) CronTab으로 실행시 스크립트 절대 경로를 가져올것.

SCRIPTPATH=$( cd "$(dirname "$0")" ; pwd -P ) 


(4) 스크립트에서 시간 형식 획득

TIME_YYYYMM=`date +"%Y%m"`;
TIME_YYYYMMDD=`date +"%Y%m%d"`;
TIME_YYYYMMDDHH=`date +"%Y%m%d%H"`; 


(5) 파일 이름 가져오기

FILE_NAME=${0##*/};


(6) 경로 존재하면 넘어가고 없으면 생성하기 

if [ ! -d "$(prop 'app.exc.path')" ]; then mkdir "$(prop 'app.exc.path')"; fi


(7) 실행시간 확인하기

BEGIN_TIME=`date +"%s%N"`; 
 ~ 실행 내용 ~ 
END_TIME=`date +"%s%N"`; ELAPSED=`echo "($END_TIME - $BEGIN_TIME) / 1000000" | bc`; ELAPSEDSEC=`echo "scale=6;$ELAPSED / 1000" | bc | awk '{printf "%.6f", $1}'`; 
printf "%-20s %-40s %-3s %-4.6f %-3s\n" `date +'%Y-%m-%d(%H:%M:%S)'` ${FILE_NAME} $SERVER_REGION_NAME $ELAPSEDSEC sec 

(8) Mysql 접속하기 

SQL="SELECT ~ " 
/usr/bin/mysql -h 호스트네임 -P 포트 -u 유저 -p비밀번호 데이터베이스명 -e "$SQL"


(9) Mysql 결과 CSV 로 저장하기

Mysql "결과 쿼리" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > $(prop 'app.csv.path')CONN_STATE_${SERVER_REGION_NAME}_${TIME_YYYYMMDDHH}.csv 

-> 형식은 " 으로 앞 뒤를 감싸줍니다.

(10) 예시
cat test.properties

############################################################ 
# File Name : test.properties                               # 
############################################################ 
# Path Properties                                          # 
#==========================================================# 
app.check=properties 
app.exc.path=/workspace/cron/ 
app.csv.path=/workspace/cron/csv/ 
app.log.path=/workspace/cron/log/ 

#==========================================================# 
# Region Properties                                        # 
#==========================================================# 
server.region.name=test 

#==========================================================# 
# RDS Properties                                           # 
#==========================================================# 
aws.rdb.host=호스트명 
aws.rdb.user=유저명 
aws.rdb.pw=비밀번호 
aws.rdb.port=포트 
aws.rdb.db=디비명 

cat TEST.sh

#!/usr/bin/env bash 
#=======================================================================# 
# File Name : TEST.sh                                       # 
#=======================================================================# 
# Script initialization                                                 # 
#=======================================================================# 
SCRIPTPATH=$( cd "$(dirname "$0")" ; pwd -P ) 

if [ -z "$1" ]; then echo "[ERROR]Parameter required."; exit 1; fi 
ENV=${1}; 
function prop { grep "${1}" ${SCRIPTPATH}/${ENV}.properties|cut -d'=' -f2; } 
if [ -z "$(prop 'app.check')" ]; then exit 1; fi 

TIME_YYYYMM=`date +"%Y%m"`; 
TIME_YYYYMMDD=`date +"%Y%m%d"`; 
TIME_YYYYMMDDHH=`date +"%Y%m%d%H"`; 
FILE_NAME=${0##*/}; 
 
SERVER_REGION_NAME="$(prop 'server.region.name')"; 
SQL="SELECT sysdate FROM dual" 

#=======================================================================# 
# Make CSV File                                                         # 
#=======================================================================# 
BEGIN_TIME=`date +"%s%N"`; 

/usr/bin/mysql -h $(prop 'aws.rdb.host') -P $(prop 'aws.rdb.port') -u $(prop 'aws.rdb.user') -p$(prop 'aws.rdb.pw') $(prop 'aws.rdb.db') -e "$SQL" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > $(prop 'app.csv.path')_${SERVER_REGION_NAME}_${TIME_YYYYMMDDHH}.csv 

END_TIME=`date +"%s%N"`; ELAPSED=`echo "($END_TIME - $BEGIN_TIME) / 1000000" | bc`; ELAPSEDSEC=`echo "scale=6;$ELAPSED / 1000" | bc | awk '{printf "%.6f", $1}'`; 

printf "%-20s %-40s %-3s %-4.6f %-3s\n" `date +'%Y-%m-%d(%H:%M:%S)'` ${FILE_NAME} $SERVER_REGION_NAME $ELAPSEDSEC sec >> $(prop 'app.log.path')${TIME_YYYYMMDD}.log; 

#=======================================================================# 
# Script End                                                            # 
#=======================================================================# 

exit 0;