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