Presentation is loading. Please wait.

Presentation is loading. Please wait.

Shell Programming Concept of the Shell Environment of Shell

Similar presentations


Presentation on theme: "Shell Programming Concept of the Shell Environment of Shell"— Presentation transcript:

1 Shell Programming Concept of the Shell Environment of Shell
Shell as programming language

2 What is Shell? Shell 이란 ? Shell의종류 Shell 의 기능 명령어 해석기
Bourne Shell  Bourne Again Shell (bash) ($) csh  확장 csh (tcsh) (%) Korn Shell, V Shell…. 기본기능이나 작동법은 동일 Shell 의 기능 내부명령, 외부명령 실행  명령프롬프트 (whereis !) 여러명령 연결 – 파이프(|) 입/출력 리다이렉션 ( >,<,>>,<<,2> ) : 명령방향 전환 특수문자 해석 및 치환, 명령어 치환 지역/환경변수 관리 스크립트 프로그래밍 언어  자동화 작업

3 Shell Environments Shell 프롬프트 Meta Characters
# echo SHELL  echo는 뒤에 나오는 문자열 출력 # echo $SHELL  ‘$’는 뒷단어를 변수로 인식하고 변수내용 출력 Meta Characters Shell이 해석하는 특수한 기능을 가진 문자  $ 메타문자 해석 금지  \ , “”, ‘’ 예) #echo \$SHELL

4 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

5 Path 현재 path 관련 변수 확인 path 디렉토리 추가 개인별 별칭(alias) 설정 단축명령어 등록
% echo $PATH path 디렉토리 추가 전체 사용자에게 추가 : /etc/profile 편집 특정 사용자에게 추가 : ~/.bash_profile 편집 현재 로그에서만 추가 (로그아웃시 소멸) % PATH=$PATH:<추가할 디렉토리> 개인별 별칭(alias) 설정 단축명령어 등록 ~/.bashrc 편집 및 활성화( . .bashrc) 예) alias lsa=‘ls –a‘ 사용자 프롬프트 변경 절대경로 표시 : /etc/bashrc 편집 \W] \\$  \$PWD] \\$

6 Logout and Commands History
로그아웃시의 실행 ~/.bash_logout 편집 도스키 및 자동 완성 도스키 기존사용 명령어 다시불러오기 화살표 사용 자동완성 일부 앞글자만 입력후 [TAB] 키 사용 디렉토리 이동시 편리함

7 Functionalities of Shell
Login시 명령어 해석 및 실행 기능 Kernel 및 응용프로그램과의 인터페이스 프로그래밍 언어로서의 Shell Sh(Bourne Shell) Csh, tcsh, zsh Ksh, bash

8 Pipe & Redirection ps | sort |more ls –l > out.txt
Ps >> out.txt 표준에러 출력 redirection, 2>와 동일 Kill – > out.txt 2>&1 Kill – > o ut.txt 2>error.txt

9 Shell as programming Language
>sh <enter> 예제 $ for i in * : 현재 디렉토리의 모든 파일 > do : for의 do > if grep -l Linux $i : if문 > then > more $i : 조건 만족시 실행 > fi : if의 닫음 > done : do 의 닫음 결과 $

10 Making Shell Script 위 예제 for i in * do if grep -l Linux $i then
# exam1.sh for i in * do if grep -l Linux $i then more $i fi done exit 0

11 Running Shell Script /bin/sh exam1.sh chmod +x exam1.sh ./exam1.sh <return>

12 Shell Programming 사용 명령어 프로그래밍 언어로서 일반적인 형식 Shell 내장명령어 + Linux 명령어
변수, 제어문,리스트, 함수, 내장명령어

13 Variables 선언 변수의 호출 별도 선언 없음(최초에는 변수명만 표기) 일반적으로 character string변수임
$변수명 Ex: foo=‘today’ echo $foo #!/bin/sh foo="Hello World" echo $foo #unset foo foo=

14 Variables 답 $변수명, “$변수명” ‘$변수명’ 변수 사용예 #!/bin/sh myvar="Hi there"
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

15 Environment $HOME : 사용자의 홈 디렉토리 $PATH : 디렉토리 목록 $PS1, $PS2 : 프롬프트 $0 : Shell 스크립트/명령어 이름 $# :전달된 파라메터 수 $$ : Shell 스크립트 프로세스 번호 echo 명령어로 실행

16 Parameter Variables $1, $2, … : 스크립트에 주어진 파라메터 $* : 모든 파라메터 #!/bin/sh
salutation="Hello" echo $salutation echo “Process Id is $$” echo "The program $0 is now running" echo "The second parameter was $2" echo "The first parameter was $1" echo "The parameter list was $*" echo "The user's home directory is $HOME" echo "Please enter a new greeting" read salutation echo "The script is now complete" exit 0

17 Conditional Statement: if
구조 test 문 test –f fred.c [ -f fred.c ] if condition then statement else fi

18 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

19 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

20 산술비교 Test Statements 스트링 비교 exp1 –eq exp2 exp1 –ne exp2
string1 = string2 string1 != string2 -n string : null 아니면 참 -z string : null 이면 참 산술비교 exp1 –eq exp2 exp1 –ne exp2 exp1 –gt exp2 ef: -ge, -lt –le ! expression

21 Iteration : for 형식 for variable in values do statement done #!/bin/sh
for foo in bar fud 43 do echo $foo done exit 0 for variable in values do statement done

22 for : Examples #!/bin/sh for foo in bar fud 43 do echo $foo done
exit 0 ---- 결과 bar fud 43

23 Iteration: while 형식 while condition; do statement done #!/bin/sh
echo "Enter Password" read trythis while [ "$trythis" != "secret" ]; do echo "Sorry, try again" done exit 0 while condition; do statement done

24 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 until condition do statement done

25 Selection Statement: Case
형식 case variable in pattern [ | pattern] ... ) statement;; ... esac

26 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

27 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

28 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 rm –f file_one exit 0

29 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

30 Statement Block 형식 function_name ( ) { statement ... }
AND, OR 리스트를 함수 형태로 형식 function_name ( ) { statement ... }

31 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" elif echo "Never mind" fi exit 0

32 Internal and External Commands
명령어 일반적인 Linux 명령어(외부명령어) Shell 내부 명령어 break Shell 스트립트 수행시 종료 : Null 명령어, true로 실행 결과

33 Internal and External Commands
• (dot) 명령어 명령어 수행 : >. ./shell_script echo String 프린트 = C언어에서 printf와 유사 eval foo= echo $foo x=foo y='$'$x echo $y x=foo eval y='$'$x echo $y

34 Internal and External Commands
exec Shell 스크립트 내에서 명령어 수행 스트립트의 다음 행부터 수행 안함 #!/bin/sh echo "first" exec wall "Hi there this is test" echo "second" exit 0

35 Internal and External Commands
Exit n Shell 스크립트 수행 종료 n=0 : 성공적인 종료 1<n<125 : 사용 가능 n=126 : 파일이 실행 불가능 n=127 : 명령이 발견되지 못함 n<128 : 시그널 발생

36 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"

37 Internal and External Commands
expr 인수를 수식으로 평가 expr 758 set : Shell을 위한 파라메터 변수 설정 #!/bin/sh echo The date today date is $(date) set $(date) echo The month is $2 exit 0

38 Internal and External Commands
shift 파라메타 변수 값을 한단계 왼쪽으로 $2는 $1으로 단, $0는 변경 불가 사용 : shift trap Signal이 수신될 때 수행 반복문 수행시 signal수신하면 위의 trap문 수행 형식 : trap command signal

39 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

40 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

41 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개씩

42 Commands in Shell Scripts
sort 하나 혹은 둘 이상 파일의 내용의 순서화 예제 : sort –t: +0 –2 /etc/passwd delimeter :, 1번째부터 2번째 필드로 그외 join, merge, uniq

43 Commands in Shell Scripts
tr 변환 예 : tr “[ ]” “[\012]” < chapter1 | sort| uniq -c


Download ppt "Shell Programming Concept of the Shell Environment of Shell"

Similar presentations


Ads by Google