Shell Programming

Download Report

Transcript Shell Programming

Shell
Programming
Concept of the Shell
Environment of Shell
Shell as programming language
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
What is Shell?
 Shell 이란 ?
 명령어 해석기
 시스템과 사용자간의 대화창구 == Shell 인터페이스
 Login시 명령어 해석 및 실행 기능
 Kernel 및 응용프로그램과의 인터페이스
 프로그래밍 언어로서의 Shell
 Shell의종류




Bourne Shell  Bourne Again Shell (bash) ($)
csh  확장 csh (tcsh) (%)
Korn Shell, V Shell….
기본기능이나 작동법은 동일
Linux Programming, Spring 2009
2/42
Functionalities of Shell
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 Login시 명령어 해석 및 실행 기능
 Kernel 및 응용프로그램과의 인터페이스
 프로그래밍 언어로서의 Shell
Linux Programming, Spring 2009
3/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
What is Shell?
 Shell 의 기능






내부명령, 외부명령 실행  명령프롬프트 (whereis !)
여러명령 연결 – 파이프(|)
입/출력 리다이렉션 ( >,<,>>,<<,2> ) : 명령방향 전환
특수문자 해석 및 치환, 명령어 치환
지역/환경변수 관리
스크립트 프로그래밍 언어  자동화 작업(batch processing)
Linux Programming, Spring 2009
4/42
Shell Environments
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 Shell 프롬프트
 # echo SHELL
 echo는 뒤에 나오는 문자열 출력
 # echo $SHELL
 ‘$’는 뒷단어를 변수로 인식하고 변수내용 출력
 Meta Characters
 Shell이 해석하는 특수한 기능을 가진 문자  $
 메타문자 해석 금지  \ , “”, ‘’
예) #echo
\$SHELL
Linux Programming, Spring 2009
5/42
Shell Environments
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 Linux의 기본 Shell
: GNU Bourne Again Shell (/bin/bash)
 C 문법을 많이 이용
 bash의 환경설정 파일
 사용자별 환경설정 파일 (cd ; ls –aF)
•
•
•
•
.bash_logout, .bash_profile, .bashrc
원본파일 /etc/skel/ 디렉토리에 존재
새로운 사용자 추가시마다 각 사용자의 홈디렉토리에 복사됨.
“.”으로 시작하는 파일은 hidden file
 모든사용자 공통의 환경설정 파일
• /etc/profile , /etc/bashrc
 환경설정 파일 인식 순서
 /etc/profile  ~/.bash_profile  ~/.bashrc  /etc/bashrc
Linux Programming, Spring 2009
6/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
Path
 현재 path 관련 변수 확인
 % echo $PATH
 path 디렉토리 추가
 전체 사용자에게 추가 : /etc/profile 편집
 특정 사용자에게 추가 : ~/.bash_profile 편집
 현재 로그에서만 추가 (로그아웃시 소멸)
• % echo $PATH
• % PATH=$PATH:<추가할 디렉토리>
 개인별 별칭(alias) 설정
 단축명령어 등록
 ~/.bashrc 편집 및 활성화( . .bashrc)
예) alias lsa=‘ls –a‘
 사용자 프롬프트 변경
 절대경로 표시 : /etc/bashrc 편집
• PS1=“[\u@\h \W] \\$
 PS1=“[\u@\h \$PWD] \\$
Linux Programming, Spring 2009
7/42
Logout and Commands History
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 로그아웃시의 실행
 ~/.bash_logout 편집
 도스키 및 자동 완성
 도스키
• 기존사용 명령어 다시불러오기
• 화살표 사용
 자동완성
• 일부 앞글자만 입력후 [TAB] 키 사용
• 디렉토리 이동시 편리함
Linux Programming, Spring 2009
8/42
Pipe & Redirection
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 ps | sort |more
 ls –l > out.txt
 Ps >> out.txt
 표준에러 출력 redirection, 2>와 동일
 Kill –9 1234 > out.txt 2>&1
 Kill –9 1234 > o ut.txt 2>error.txt
Linux Programming, Spring 2009
9/42
Shell as programming Language
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
sh
<enter>
Cd /etc
$ for i in *
> do
> grep Linux $i
> done
결과
$
: 현재 디렉토리의 모든 파일
: for의 do
: do 의 닫음
Linux Programming, Spring 2009
10/42
Making Shell Script
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 위 예제
#!/bin/sh
# exam1.sh
# 예제 1
for i in *
do
if grep -l Linux $i
then
more $i
fi
done
exit 0
Linux Programming, Spring 2009
11/42
Running Shell Script
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 /bin/sh exam1.sh
 chmod +x exam1.sh
 ./exam1.sh <return>
Linux Programming, Spring 2009
12/42
Shell Programming
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 사용 명령어
 Shell 내장명령어 + Linux 명령어
 프로그래밍 언어로서 일반적인 형식
 변수, 제어문,리스트, 함수, 내장명령어
Linux Programming, Spring 2009
13/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
Variables
 선언
 별도 선언 없음(최초에는 변수명만 표기)
 일반적으로 character string변수임
 변수의 호출
 $변수명
 Ex:
foo=‘today’
echo $foo
#!/bin/sh
foo="Hello World"
echo $foo
#unset foo
foo=
echo $foo
Linux Programming, Spring 2009
14/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line



$변수명, “$변수명”
‘$변수명’
변수 사용예
Variables
#!/bin/sh
myvar="Hi there"
echo $myvar
echo ${myvar}
echo "$myvar"
echo '$myvar'
 답
Hi there
Hi there
Hi there
$myvar
$myvar
Enter some text
Hello World
$myvar now equals Hello World
echo \$myvar
echo Enter some text
read myvar
echo '$myvar' now equals
$myvar
exit 0
Linux Programming, Spring 2009
15/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line







Environment
$HOME : 사용자의 홈 디렉토리
$PATH : 디렉토리 목록
$PS1, $PS2 : 프롬프트
$0 : Shell 스크립트/명령어 이름
$# :전달된 파라메터 수
$$ : Shell 스크립트 프로세스 번호
echo 명령어로 실행
Linux Programming, Spring 2009
16/42
Parameter Variables
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 $1, $2, … : 스크립트
에 주어진 파라메터
 $* : 모든 파라메터
#!/bin/sh
sal="Hello"
echo $sal
echo "The program is $0"
echo “2: $2"
echo "1: $1"
echo "The parameter list: $*"
echo "The Home Dir: $HOME"
echo "Please enter a new greeting"
read sal
echo $sal
echo "complete…"
Linux Programming, Spring 2009
17/42
Conditional Statement: if
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 구조
 test 문
if condition
 test –f fred.c
 [ -f fred.c ]
then
statement
else
statement
fi
Linux Programming, Spring 2009
18/42
If Statements: Examples
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
#!/bin/sh
echo "Is it morning? Please answer yes or no"
read timeofday
if [ $timeofday = "yes" ]; then
echo "Good morning"
else
echo "Good afternoon"
fi
exit 0
Linux Programming, Spring 2009
19/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
-b file
-c file
-d file
-f file
-g file
-k file
-p file
-r file
-s file
-t n
-u file
-w file
-x file
Test statement
: file is a block special file
: file is a character special file
: file exists and is a directory
: file exists and is a file
: file has the set-group-id bit set
: file has the sticky bit set
: file is a named pipe
: file is readable
: file is greater than 0 byte
: n is a file descriptor, 0=keyboard input
: file has the set-user-id
: file is writable
: file is executable
Linux Programming, Spring 2009
20/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
Test Statements
 스트링 비교





string1 = string2
string1 != string2
-n string : null 아니면 참
-z string : null 이면 참
산술비교




exp1 –eq exp2
exp1 –ne exp2
exp1 –gt exp2 ef: -ge, -lt –le
! expression
Linux Programming, Spring 2009
21/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
Iteration : for
 형식
for variable in values
do
statement
done
#!/bin/sh
for foo in bar fud 43
do
echo $foo
done
exit 0
Linux Programming, Spring 2009
22/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
for : Examples
#!/bin/sh
for foo in bar fud 43
do
echo $foo
done
exit 0
---- 결과
bar
fud
43
Linux Programming, Spring 2009
23/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 형식
Iteration: while
#!/bin/sh
echo "Enter Password"
while condition; do
read trythis
statement
done
while [ "$trythis" !=
"secret" ]; do
echo "Sorry, try again"
read trythis
done
exit 0
Linux Programming, Spring 2009
24/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 형식
#!/bin/sh
until condition
until who | grep "$1" >
/dev/null
do
do
sleep 60
statement
done
Iteration: until
done
# Now ring the bell and announce
the unexpected user.
echo -e \\a
echo "***** $1 has just logged
in *****"
exit 0
Linux Programming, Spring 2009
25/42
Selection Statement: Case
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 형식
case variable in
pattern [ | pattern] ... ) statement;;
pattern [ | pattern] ... ) statement;;
...
esac
Linux Programming, Spring 2009
26/42
Case: Examples
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
#!/bin/sh
echo "Is it morning? Please answer yes or no"
read timeofday
case $timeofday in
"yes") echo "Good Morning";;
"no" ) echo "Good Afternoon";;
"y"
) echo "Good Morning";;
"n"
) echo "Good Afternoon";;
*
) echo "Sorry, answer not recognised";;
esac
exit 0
Linux Programming, Spring 2009
27/42
Case: Examples
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
#!/bin/sh
echo "Is it morning? Please answer yes or no"
read timeofday
case $timeofday in
"yes" | "y" | "Yes" | "YES" ) echo "Good Morning";;
"n*" | "N*" )
Afternoon";;
echo "Good
* )
not recognised";;
echo "Sorry, answer
esac
exit 0
Linux Programming, Spring 2009
28/42
Listing Commands: AND &&
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 다수 명령어 결합, 앞명령어 성공시 뒷명령어 수행
 형식 :
statement1 && statement2 …
#!/bin/sh
touch file_one
rm -f file_two
if [ -f file_two ] && echo "hello" || echo
"there"
then;
echo "in if"
Else;
echo "in else"
fi
exit 0
Linux Programming, Spring 2009
29/42
Listing Commands: OR ||
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 하나의 명령이 성공할 때까지 수행, 나머지 수행안함
 형식 :
statement1 || statement2 || …
#!/bin/sh
rm -f file_one
if [ -f file_one ] || echo "hello" || echo "there"
then;
echo "in if"
else; echo "in else"
fi
exit 0
Linux Programming, Spring 2009
30/42
Statement Block
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 AND, OR 리스트를 함수 형태로
 형식
function_name ( ) {
statement
...
}
Linux Programming, Spring 2009
31/42
Statement Block: Examples
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
#!/bin/sh
echo "Original parameters are
$*"
yes_or_no() {
echo "Parameters are $*"
if yes_or_no "Is your name $1"
while true
then
do
echo -n "Enter yes or no“ ; read
“ y” | ”yes” ) return 0;;
* )
no"
echo "Hi $1"
else
case "$x" in
“n” | “no” )
x
return 1;;
echo "Never mind"
fi
echo "Answer yes or
exit 0
esac
done
}#yes_or_no()
Linux Programming, Spring 2009
32/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 명령어
 일반적인 Linux 명령어(외부명령어)
 Shell 내부 명령어
 break
 Shell 스트립트 수행시 종료
 :
 Null 명령어, true로 실행 결과
Linux Programming, Spring 2009
33/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 • (dot) 명령어
 명령어 수행 : >. ./shell_script
 echo
 String 프린트 = C언어에서 printf와 유사
 eval
foo=10
$foo
답:
foo=10
답: 10
x=foo
x=foo
y='$'$x
eval y='$'$x
echo $y
echo $y
Linux Programming, Spring 2009
34/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 exec
 Shell 스크립트 내에서 명령어 수행
 스트립트의 다음 행부터 수행 안함
#!/bin/sh
echo "first"
exec wall "Hi there this is
test"
echo "second"
exit 0
Linux Programming, Spring 2009
35/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 Exit n






Shell 스크립트 수행 종료
n=0 : 성공적인 종료
1<n<125 : 사용 가능
n=126 : 파일이 실행 불가능
n=127 : 명령이 발견되지 못함
n<128 : 시그널 발생
Linux Programming, Spring 2009
36/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 export
 지정된 변수를 서브Shell에서 유효하게
# Shell Program export1.sh
#!/bin/sh
foo="The first meta-syntactic variable"
export bar="The second meta-syntactic variable"
export2
#!/bin/sh
# Shell Program export2.sh
echo "$foo"
echo "$bar"
Linux Programming, Spring 2009
37/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 expr
 인수를 수식으로 평가
expr 327 + 431
758
 set : Shell을 위한 파라메터 변수 설정
#!/bin/sh
echo The date today date is $(date)
set $(date)
echo The month is $2
exit 0
Linux Programming, Spring 2009
38/42
Internal and External Commands
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 shift
 파라메타 변수 값을 한단계 왼쪽으로
 $2는 $1으로 단, $0는 변경 불가
 사용 : shift
 trap
 Signal이 수신될 때 수행
 반복문 수행시 signal수신하면 위의 trap문 수행
 형식 : trap command signal
Linux Programming, Spring 2009
39/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
Trap 문 예제
#!/bin/sh
trap -INT
trap 'rm -f /tmp/my_tmp_file_$$'
INT
echo creating file
/tmp/my_tmp_file_$$
echo creating file
/tmp/my_tmp_file_$$
date > /tmp/my_tmp_file_$$
echo "Press interrupt (Ctrl-C) to
interrupt...."
while [ -f /tmp/my_tmp_file_$$ ];
do
echo File exists
date > /tmp/my_tmp_file_$$
echo "Press interrupt
(Ctrl-C) to
interrupt...."
while [ -f
/tmp/my_tmp_file_$$ ];
do
echo File exists
sleep 1
done
sleep 1
echo We never get here
done
echo The file no longer exists
exit 0
Linux Programming, Spring 2009
40/42
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
Debugging
 특별한 디버깅 도구 없음
 에러 있는 행의 번호를 출력
 그외 방법 : 명령라인 옵션
sh -n <script> : 형식 검사만,실행안함
sh -v <script> : 실행전 스크립트 출력
sh -x <script> : 처리후 명령라인 출력
 스크립트 내 set 옵션
set -o noexec or set -n
set -o verbose or set -v
set -o xtrace or set -x
set -o nounset or set -u
Linux Programming, Spring 2009
41/42
Commands in Shell Scripts
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 cut
 파일의 특정 필트 추출
 -d 에 delimeter 정의 가능
 예제 : grep root /etc/passwd | cut –f1,5 –d:
ls –l | cut –c1-15,55-
 paste
 예제 : ls –a | paste - - ; - 출력 라인 2개씩
Linux Programming, Spring 2009
42/42
Commands in Shell Scripts
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 sort
 하나 혹은 둘 이상 파일의 내용의 순서화
 예제 : sort –t: +0 –2 /etc/passwd
delimeter :, 1번째부터 2번째 필드로
 그외
 join, merge, uniq
Linux Programming, Spring 2009
43/42
Commands in Shell Scripts
RUNNING HEADER, 14 PT., ALL CAPS, Line Spacing=1 line
 tr
 변환
 예:
tr “[ ]” “[\012]” < chapter1 | sort| uniq –c
\012 : form feed, new line
Linux Programming, Spring 2009
44/42