검색결과 리스트
shell script에 해당되는 글 6건
- 2019.04.16 shell script - for 문 사용 예시 (1)
- 2019.04.16 shell script 작성법 - 수식 계산 & 문자열 조작
- 2017.09.17 자주 사용하는 bash shell script 기능
- 2017.05.01 shell script에서 mysql query 실행하기
- 2016.03.20 리눅스에서 date 명령어 사용하기
- 2015.12.26 shell script로 이메일 보내기
글
shell script - for 문 사용 예시
쉘 스크립트에서 for문 사용 예시
- 기본
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
- 배열 사용하기
#!/bin/bash
arrayname=(value1 value2)
for i in ${arrayname[@]}
echo "Welcome $i times"
done
- 숫자범위 사용하기
#!/bin/bash
for i in {2000..2011};do echo " $i times";done
- 명령어 결과 사용하기
#!/bin/bash
for entry in $stockdir/*;do echo " $entry times";done
- 일반 반복문 형식 사용하기
#!/bin/bash
for (( i=0; i<100; i++ ));do echo " $i times";done
#!/bin/bash
for (( i=0; i<100; i=i+5 ))
do
j=$((i + 4));
echo "alter table 테이블이름 add column age_"$i"_"$j"_totalcnt bigint DEFAULT NULL;";
echo "COMMENT ON COLUMN 테이블이름.age_"$i"_"$j"_totalcnt IS '"$i" - "$j"세 총 인구수';"
done
설정
트랙백
댓글
글
shell script 작성법 - 수식 계산 & 문자열 조작
shell script 작성법
수식 계산 & 문자열 조작
수식 계산은 아래 방식중 하나를 사용해서 작성한다.
num=$((num1 + num2))
num=$(($num1 + $num2))
num=$((num1 + 2 + 3))
문자열 시작에서부터 정규 표현식에 매칭되는
문자열조각(substring)의 길이 계산하기
- expr match "$string" '$substring'
- $substring 은 정규 표현식입니다.
- expr "$string" : '$substring'
- $substring 은 정규 표현식입니다.
- 예시 1) 'abc[A-Z]*.2' 정규표현식에 매칭하는 문자열 길이 구하기
- abc 로 시작하고
- [A-Z] A에서 Z까지 영어대문자가 0번 이상 반복되며
- 2로 끝남
- stringZ에서 abcABC12 에 해당되고 문자열 조각의 길이는 8임
- stringZ=abcABC123ABCabc
- echo `expr match "$stringZ" 'abc[A-Z]*.2'` # 8
- echo `expr "$stringZ" : 'abc[A-Z]*.2'` # 8
예시 2) 문자열에서 sorted 앞에 있는 문자열 길이만 계산
echo `expr match "Autech_Corporation_body.txt.sorted" '.*sorted'`
34
echo `expr match "Autech_Corporation_body.txt" '.*sorted'`
0
참고) ttps://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/string-manipulation.html
설정
트랙백
댓글
글
자주 사용하는 bash shell script 기능
자주 사용하는 셸스크립트 기능
문자열 비교
#!/bin/bash
if [ "$1" == "yesterday" ]; then
today=`date '-d yesterday' '+%d %b %Y'`
todayfile=`date '-d yesterday' '+%y_%m_%d'`
else
today=`date '+%d %b %Y'`
todayfile=`date '+%y_%m_%d'`
fi
파일 경로에서 파일 이름만 추출
fspec="/exp/home1/abc.txt"
fname="${fspec##*/}"
설정
트랙백
댓글
글
shell script에서 mysql query 실행하기
shell script에서 mysql query를 사용하는 스크립트 예시를 정리해둔다.
쉘 스크립트 에서 사용한다고 mysql 사용 방법이 별다를 건 없고
query 내에서 "를 사용하지 않고 '를 사용하는 정도만 주의하면 된다.
#!/bin/bash
lastday_mysql=`date -d '1 day ago' '+%Y-%m-%d'`
today_query="SELECT * FROM table where 날짜 = '${lastday_mysql}' into outfile '/tmp/table.csv' fields terminated by ',';"
echo $today_query
mysql -u uid -p{passwd} -D database -e "${today_query}"
mysql query의 결과를 변수를 받고 싶을 경우
areas=$(mysql -u uid -p{passwd} -D database" -se "select distinct(area) from Price")
echo ${areas}
...
설정
트랙백
댓글
글
리눅스에서 date 명령어 사용하기
date는 리눅스에서 시스템 시간을 세팅하거나 출력하기 위해 사용하는 함수이다.
man date를 하면 아래와 같은 기본 사용법이 나온다.
주로 -d option으로 원하는 시간 문자열로 조정한후
format옵션으로 원하는 형태로 시간을 출력하는 방식으로 사용하고 있다.
아무 인자 없이 사용하면 현재 시간이 출력된다.
DATE(1) User Commands DATE(1)
NAME
date - print or set the system date and time
SYNOPSIS
date [OPTION]... [+FORMAT]
date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
DESCRIPTION
Display the current time in the given FORMAT, or set the system date.
Mandatory arguments to long options are mandatory for short options too.
-d, --date=STRING
display time described by STRING, not 'now'
-f, --file=DATEFILE
like --date once for each line of DATEFILE
-s, --set=STRING
set time described by STRING
-u, --utc, --universal
print or set Coordinated Universal Time
--help display this help and exit
--version
output version information and exit
아래는 -d 옵션으로 시간 표현을 문자열로 출력하는 예시이다.
# date
2016. 01. 24. (일) 12:46:30 KST
# 과거
date -d 'yesterday' # 어제
date -d '2 day ago' # 2일전
date -d '1 week ago' # 1주일전
date -d '1 month ago' # 1달전
date -d '1 year ago' # 1년전
date -d '10 second ago' # 10초전
date -d '20 minute ago' # 20분전
date -d '30 hour ago' # 30시간전
date -d '3 year 7 month ago' # 3년 7개월전
#미래
# 특정일 기준
# date -d '2015-01-25 + 1 day'
2015. 01. 26. (월) 00:00:00 KST
# date -d '2015-01-25 - 1 day'
2015. 01. 24. (토) 00:00:00 KST
# date -d '2015-01-25 - 1 month'
2014. 12. 25. (목) 00:00:00 KST
# date -d '2015-01-25 + 1 month'
2015. 02. 25. (수) 00:00:00 KST
f참고: http://steadypost.net/post/knowhow/id/8/관련 option은 아래와 같다
시간 표현을 하는 format 옵션의 사용방법은 아래와 같다.
FORMAT controls the output. Interpreted sequences are:
%% a literal %
%a locale's abbreviated weekday name (e.g., Sun)
%A locale's full weekday name (e.g., Sunday)
%b locale's abbreviated month name (e.g., Jan)
%B locale's full month name (e.g., January)
%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
참고로 쉘스크립트에서 시간표현을 변수에 담는 방법은 아래와 같다.
yesterday=$(date -d '1 day ago')
또는
yesterday=`date -d '1 day ago'`
설정
트랙백
댓글
글
shell script로 이메일 보내기
뉴스 업데이트 결과를 메일로 보내는 쉘 스크립트를 작성하였다.
스크립트를 실행하기 전에 mail 프로그램이 깔려있어야 한다.
#!/bin/bash
subject="today update summary"
email="user@naver.com"
filename="/tmp/message.txt"
updated_cnt=`grep -c "there is new" /home/log/sort_date.log`
echo "updated news count:${updated_cnt}" > ${filename}
#메일 발송하기
mail -s "$subject" "$email" < $filename
참고로 메일설치 삽질과정도 기록해둔다.
apt-get install mailutils
위 명령어를 입력하면 아래 설정창이 나온다.
이 중에서 하나를 선택해야 한다.
SMTP를 사용해서 메일을 보내고 받으려고 하면
Internet Site 를 선택하면 된다.
기존 설정이 없던 상태에서 No configuration 을 선택했더니 아래와 같은 에러가 발생하였다.
참고로 /var/log/mail.err 에서 메일 관련 에러 메세지를 확인할 수 있다.
#echo "Test" | mail -s "Test" username@naver.com
mail: cannot send message: Process exited with a non-zero status
/var/log# ll *mail*
-rw-r----- 1 syslog adm 214 12월 25 16:33 mail.err
-rw-r----- 1 syslog adm 214 12월 25 16:33 mail.log
vi mail.err
postfix/sendmail[11425]: fatal: open /etc/postfix/main.cf: No such file or directory
postfix/sendmail[11453]: fatal: open /etc/postfix/main.cf: No such file or directory
검색해보니 메일 보내기 설정이 제대로 되어있지 않아서 그런것이라고 해서
sudo dpkg-reconfigure postfix
로 다시 위 설정창을 띄운 후 Internet site로 설정을 변경했다.
참고: http://jonsview.com/how-to-setup-email-services-on-ubuntu-using-postfix-tlssasl-and-dovecot
잘 보고 갑니다~~