shell programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/sp_taesoo/prct_04_shell... ·...

50
SHELL programming

Upload: others

Post on 05-Jan-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

SHELL programming

Page 2: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 2

Shell 이란 ? Redirection & Pipes Shell Programming 변수 조건 프로그램 제어 리스트 함수 Shell 에 내장된 명령 Here documents

Content

Page 3: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 3

User 와 UNIX(Linux) 사이의 인터페이스로 작동하는 프로그램 .– 사용자는 shell 을 통하여 OS 가 실행할 명령을 입력– Windows(command 환경 ) 의 명령 프로프트와 비슷 – [ue20@zeus ~]$ vs. C:\windows>_

대부분의 shell 들은 Bourne shell 로부터 파생됨– bash, csh, sh(Bourne), zsh, etc.

Shell 은 두 가지 역할을 한다 .– 명령어 처리기– 고급 프로그래밍 언어

Shell 이란 ?

[ 실습 1] 현재 사용중인 bash 쉘의 버전 확인[ue20@zeus ~]$ /bin/bash --version

Page 4: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 4

File Descriptor– Process 가 File 이나 Device 를 access 하기 위해 사용– Standard File Descriptor– stdin(0) : 표준 입력 ( 예 , 키보드 )– stdout(1) : 표준 출력 ( 예 , 모니터 )– stderr(2) : 표준 에러 출력 ( 예 , 에러 메시지 )

Redirection– 출력 재지정– 입력 재지정– >, >> (stdout 을 파일로 저장 또는 추가 )– < ( 파일을 stdin 으로 전달 )

Pipe ( | )– Process 연결 (stdout 을 stdin 으로 전달 )– Process 간의 데이터 흐름은 자동으로 조절됨

Redirection & Pipes

Page 5: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 5

Redirection & Pipe 실습

[ue20@zeus ch2]$ ls –al > lsoutput.txt[ue20@zeus ch2]$ more lsoutput.txt more 또는 cat 명령어를 통해 lsoutput.txt 내용을 확인[ue20@zeus ch2]$ more < lsoutput.txt [ue20@zeus ch2]$ ps >> lsoutput.txt[ue20@zeus ch2]$ more lsoutput.txt

현재 위치에서 다음과 같이 입력 ※ ps 명령어 : 시스템 내에서 현재 진행중인 프로세서를 보여준다 .

vim lsoutput.txt 내용

more( 또는 cat) lsoutput.txt 내용

Page 6: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

● 여러 파일 검색– find . -iname “*.txt” | xargs grep “asdf”

● Pipe $ cal > foo $ cat /dev/zero > foo $ cat < /etc/passwd $ who | cut -d' ' -f1-4 | sort | uniq | wc –l

● backtick $ echo “The date is `date`” $ echo `seq 1 10`

● Hard, soft (symbolic) link ln vmlinuz-2.6.24.4 vmlinuz ln -s firefox-2.0.0.3 firefox

Redirection & Pipe 실습

Page 7: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 7

Shell Programming 두 가지 방법– 명령을 차례 (line command) 로 입력하고 Shell 이 대화형으로 실행– 하나의 스크립트 작성 후 프로그램처럼 사용– Script 작성– 실행 파일로 만들기– 실행

Shell Programming

[ue20@zeus ch2]$ for file in * > do > if grep –l ps $file > then > more $file > fi > done

예 1. Line command[ue20@zeus ch2]$ vi first# !/bin/bash

for file in *do if grep -l ps $file then echo $file fidoneexit 0

예 2. Script 를 이용

[ 실행 ]$ /bin/sh first줄바꿈 위치 중요 !

줄바꿈 대신 ; 사용 가능

Page 8: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 8

You can use python instead.

import subprocess

subprocess.call(['ls', '-l'])subprocess.call('ls -l', shell=True)subprocess.call('echo $HOME', shell=True)subprocess.call('ls -l | grep total', shell=True)

Page 9: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 9

Python version : test.py

# !/usr/bin/pythonimport osimport subprocess as spfor filen in os.listdir("."):

if sp.call("grep -l ps '"+filen+"'>/dev/null", shell=True)==0:

print(filen)

# !/usr/bin/pythonimport osimport subprocessprint(subprocess.check_output(“ls -l”, shell=True)os.system(“ls -l”)

Python: 들여쓰기 시 탭 또는 스페이스 ( 보통 4 개 ) 를 사용할수 있는데 둘 중 하나를 정해 코드 전체에서 일관되게 사용할 것 !

Page 10: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 10

변수 : 문자열 , 숫자 , 환경 , 매개변수조건 : 쉘 부울 (Boolean)

프로그램 제어 : if, elif, for, while, until, case

리스트함수쉘에 내장된 명령명령의 결과 가져오기

Shell 문법

Page 11: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 11

Shell 변수– Shell 에서 변수는 사용할 때 선언– 변수에 초기 값을 대입할 때 변수를 만들게 된다– 모든 변수는 문자열로 간주한다 .– 숫자 값을 가지는 경우에도 문자열로 간주된다 .

– 변수는 대소문자를 구분한다 . ( 리눅스 시스템 특성 )

– 변수에 값이 부여될 때를 제외하고 , 변수를 사용할 경우 변수 앞에 ‘ $’ 의 표시를 붙여야 한다 .

– 변수에 부여된 값은 echo 명령을 통해 확인 가능 .

– 변수에 저장될 문자열 값 중 빈 칸을 포함하고 있다면 “ ”을 이용하여 값을 부여한다 .

Shell 변수

Page 12: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 12

쉘 변수 실습실습 4. 명령줄 (command line) 에 변수에 값을 설정하고 each 로 확인하기

[ue20@zeus ch2]$ VAR=Hello 값을 설정할 때 띄워 쓰면 에러 발생[ue20@zeus ch2]$ echo $VAR Hello[ue20@zeus ch2]$VAR=“Hello Hanyang Univ”[ue20@zeus ch2]$ echo $VAR Hello Hanyang Univ

Page 13: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 13

쉘 변수 실습실습 5. 스크립트를 작성해서 다양한 출력형태 확인

[ue20@zeus ch2]$ vi var_example.shmyvar=“Hi Hanyang Univ”

echo $myvarecho “$myvar”echo ‘$myvar’echo \$myvar

echo Enter some textread myvar echo ‘$myvar’ now equals $myvarexit 0

Page 14: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 14

Python version

# !/usr/bin/pythonimport osprint(os.getenv(“HOME”))Print “Enter some text”myvar=raw_input()print(myvar)

Page 15: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 15

Shell 의 환경변수– Shell Script 가 시작 될 때 일부의 변수는 환경의 값을 통해 초기화 되는데 , 이를 환경변수라 한다 .

– 사용자 정의 ( 쉘 ) 변수와 구분하기 위해 보통 대문자로 선언– 환경변수는 각 사용자 환경에 따라 값이 다르다 .

Shell 환경변수

환경변수 설명$HOME 현재 사용자의 홈 디렉토리$PATH 명령을 검색하는 디렉토리들의 목록 , ‘:’ 으로 구분된다$PS1 대개 ‘ $’ 인 명령 프롬프트$PS2 추가적인 입력을 요구할 때 사용되는 2 차 프롬프트 , 주로 ‘ >’ 이다 .

$IFS 입력 필드 구분자 . Shell 이 입력을 받아들일 때 단어를 구분하는 데사용되는 문자의 목록으로 , 대개 빈 칸 , 탭 , 새 줄 문자이다 .

$0 Shell Script 의 이름$# 전달된 파라미터의 수$$ /tmp/tmpfile_$$ 와 같이 종종 독특한 임시 파일 이름을 생성하기 위해

Script 에서 사용되는 Shell Script 의 프로세스 ID

Page 16: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 16

Shell 환경변수 실습실습 6. 환경변수 이해하기

[ue20@zeus ch2]$ echo $PATH/usr/kerberos/bin:/usr/local/bin:/bin/:/usr/bin:/usr/X11R6/bin:/home/ue20/bin[ue20@zeus ch2]$ echo $HOME/home/ue20[ue20@zeus ch2]$ cat ~/.bashrc

#Get the aliases and functionsif [ -f ~/.bash_aliases ]; then

~/.bash_aliasesfi

#User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH

[ue20@zeus ch2]$

Page 17: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 17

Python script 에서 bash 로 환경변수 export 는 불가능함 ( 단 , bash script 와 python script 를 동시에 사용하면 가능 )

Page 18: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 18

Shell 의 파라미터 변수– Script 가 파라미터를 통해 호출된다면 몇 가지 추가적인 변수가 생성되는데 이를 파라미터 변수라 한다 .

Shell 파라미터 변수

파라미터 변수 설명$1, $2, ….. Script 에 주어진 파라미터

$* 환경 변수 IFS 의 첫 문자로 구분되고 , 하나의 변수에 저장되는모든 파라미터의 목록

$@ IFS 환경 변수를 사용하지 않는 $* 에 대한 변형

Page 19: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 19

파라미터 변수 실습– Shell 상태에서 다음과 같이 명령을 실행한다 .

$IFS=h # 환경변수 IFS 를 h 로 초기화 한다 .

$set foo bar bam # 파라미터 설정 .

$echo $@

$echo "$@"

$echo $*

$echo "$*"

$unset IFS

$echo $@

$echo $*

$echo "$@"

$echo "$*"

Shell 파라미터 변수

Page 20: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 20

Shell 파라미터 변수 실습실습 7. 매개 변수와 환경 변수

[ue20@zeus ch2]$ vim vitry_var.sh

salutation=“Hello”echo $salutationecho “The Program $0 is now running”echo “The Second parameter was $2”echo “The First parameter was $1”echo “The user’s home directory is $HOME”

echo “Please enter a new greeting”read salutation

echo $salutationecho “The script is now complete”exit 0

Page 21: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 21

Shell 파라미터 변수 실습실습 7. 매개 변수와 환경 변수 결과 확인

※ 사용자 작성 스크립트 chmod 명령을 통해 권한 변경 후 수행 가능하게 만들기 [ue20@zeus ch2]$ ls -l [ue20@zeus ch2]$ chmod +x vitry_var.sh [ue20@zeus ch2]$ ls –l [ue20@zeus ch2]$ ./vitry_var.sh Hanyang Univ.

사용자 입력

Page 22: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 22

Python version

# !/usr/bin/pythonimport os,sys,stringprint(sys.argv)print(len(sys.argv))try:

print(string.join(sys.argv, ' '))print('a')print(sys.argv[0])print(sys.argv[1])print(sys.argv[2])os.system('ls')

except Exception:pass

Page 23: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 23

Shell Bool 형 확인 기능 [], test– test, [] 는 어떤 표현식이나 파일에 대해 산술비교 스트링 비교 , 파일조건 등을 확인하고 그에 대해 참 또는 거짓의 값을 리턴

Shell 조건문

예 ) 파일의 존재 유무를 확인하는 test 명령 사용법 : test –f <filename>

방법 1. 기본형if test –f fred.cthen…fi

방법 2. 축약형if [ -f fred.c]then…fi

조건형식 문자열 비교 , 산술 비교 , 파일 조건 (p79 ~ 80 table 참고 )

Page 24: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 24

If– 명령의 결과를 테스트하고 조건부로 구문의 그룹을 실행한다 .

If 구문 if condition

then

statements

else

Statements

fi

Shell 제어 구조

Page 25: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 25

If 조건문 실습실습 8. 간단한 if 조건문 사용[ue20@zeus ch2]$ vim ch2_if.sh

#!/bin/sh

echo “Is it morning? Please answer yes or no”read timeofdayif [ $timeofday = “yes” ]; then

echo “Good morning”else

echo “Good afternoon”fiexit 0

user input

Page 26: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 26

elif 조건문 실습실습 9. elif 를 사용하여 더 많은 검사를 수행하기

[ue20@zeus ch2]$ vim ch2_ex_if.sh

#!/bin/sh

echo “Is it morning? Please answer yes or no”read timeofday

if [ $timeofday = “yes” ];thenecho “Good morning”

elif [ $timeofday=“no” ];thenecho “Good afternoon”

elseecho “Sorry, $timeofday not recognized. Enter yes or no”exit 1

fi

Page 27: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 27

For– 값의 범위에 대한 반복문 수행– 값의 범위는 문자열의 집합도 가능

For 구문 for variable in values

dostatements

done

Shell 제어 구조

Page 28: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 28

for 반복분 실습실습 10. 고정된 문자열을 사용하는 for 반복문

[ue20@zeus ch2]$ vim ch2_for.sh

#!/bin/sh

for foo in bar fud 43do

echo $foodoneexit 0

[ue20@zeus ch2]$ vim ch2_for1.sh

#!/bin/sh

for foo in “bar fud 43”do

echo $foodoneexit 0

※ 변수 foo 를 만들고 for 반복문이 매번 실행 할 때마다 다른 값이 대입된다 . 따라서 위의 두 예제 결과가 다름을 알 수 있을 것이다 .

Page 29: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 29

for 반복분 실습실습 11. 와일드카드 (*) 확장을 사용하는 for 반복문

[ue20@zeus ch2]$ vim ch2_wfor.sh

for file in $(ls c*.sh)do

echo $filedoneexit 0

※ values 값으로 $(command) 을 이용하여 , 변수명 ( 여기서는 file) 은 $(ls c*.sh) 에 포함된 명령의 출력값을 이용한다 . 즉 , 현재 디렉토리 내의 c 로 시작하고 확장자가 sh 로 끝나는 (c*.sh) 모든 파일을 입력으로 해서 echo $file 출력을 한다 .

Page 30: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 30

The previous script is buggy!- 파일이름에 공백이 있는 경우 정상동작하지 않음→ for file in $(ls c*.sh) 대신 아래 문장 사용 권장 : for file in c*.sh

Python:

import globfor fname in glob.glob(“c*.sh”):

Page 31: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 31

For 문◦ 모든 shell 변수가 기본적으로 문자열로 인식하기 때문에 ,for 반복문은 문자열 집합에 대해 반복문을 수행하기에 편리◦ 하지만 , 정해진 횟수만큼 명령을 실행할 수 없음 ( 또는 외부 명령 seq 등이 필요 )

while 구문◦ while condition dostatementsdone

Shell 제어 구조

# !/bin/shfor foo in 1 2 3 4 5 6 7 8 9 10 11 12 do echo “here we go again”doneexit 0

Page 32: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 32

while 문 실습실습 12. while 문을 이용한 간단한 password 확인 프로그램 작성

[ue20@zeus ch2]$ vim ch2_pass_while.sh

#!/bin/sh

echo “Enter password”read pass

while [ “$pass” !=kokoro” ]; doecho “Sorry, try again..”read pass

doneexit -0

user input

Page 33: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 33

while 문 실습실습 13. 정해진 횟수만큼 실행해보기

[ue20@zeus ch2]$ vim ch2_count_while.sh

#!/bin/shfoo=1

while [ “$foo” –le 5 ]do

echo “Here we go again”foo=$(($foo+1))

doneexit 0

※ [ Expression1 –le Expression2 ] exp1 이 exp2 보다 작거나 같을 때까지 반복한다

Page 34: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 34

until 구문– until condition

do

statements

done

Shell 제어 구조

Page 35: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 35

Shell 제어 구조[ue20@zeus ch2]$ vim until2.sh

#!/bin/sh

until who | grep “$1” > /dev/nulldo

sleep 10doneecho –e \\aecho “$1 has just logged in”exit 0

현재 로그인 된 user 검색 명령어

첫 번째 파라미터

Page 36: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 36

Python version

# !/usr/bin/pythonimport subprocess as spimport timewhile sp.call('who | grep "'+sys.argv[1]+'"', shell=True)==1:

time.sleep(10)print(sys.argv[1]+" has just logged in")

Page 37: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 37

Case 구문– case variable in

pattern [ | pattern ] ...) statements;;

pattern [ | pattern ] ...) statements;;

...

esac

Shell 제어 구조

#!/bin/shecho “Is it morning? Please answer yes or no”read timeofday

case “$timeofday” in yes | y | Yes | YES ) echo “Good Morning”;;[nN]* ) echo “Good Afternoon”;;* ) echo “Sorry”exit 1;;

esac

[ue20@zeus ch2]$

Page 38: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 38

단순 list– 구문 1 ; 구문 2 ; 구문 3 ; ...

AND list– 구문 1 && 구문 2 && 구문 3 && ...

OR list

– 구문 1 || 구문 2 || 구문 3 || ...

Shell 리스트

$ true && echo "Yes."

Yes.

$ false || echo "Yes."

Yes.

Page 39: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 39

함수– function_name () {

statements

}

Shell 함수 [ue20@zeus ch2]$ vim function.sh#!/bin/sh

yes_or_no(){echo “Is Your Name $1?”while truedo

echo –n “Enter yes or no: ”read Xcase “$X” iny|Y|yes|Yes|YES) return 0;;n|N|no|No|NO) return 1;;*) echo “Answer yes or no”esac

done}echo “Original parameters are $*”if yes_or_no “$1”then

echo “Hi $1”else

echo “Oh! Sorry”fiexit 0

Page 40: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 40

Shell script 내의 2 가지 명령 형태 – 명령 프롬프트로부터 실행 가능한 명령– Shell script 내에 정의된 내장 명령

Shell 에 내장된 명령

Page 41: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 41

Break– 반복문을 빠져나올 수 있다 .

Shell 에 내장된 명령

[ue20@zeus ch2]$ vim break.sh

#!/bin/shfor var in 1 2 3 4 5 6 7 8 9 10do

echo “var is $var.”if [ “$var” = “5” ]then

break;fi

done

echo “Break!”exit 0~[ue20@zeus ch2]$

Page 42: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 42

: ( 콜론명령 )– 널 명령 , true 에 대한 별칭으로 조건에 대한 논리 지정

continue– 반복문에서 다음 반복에서부터 실행을 계속 한다 .

echo– 문자열과 줄 바꿈 문자를 출력

eval– 인자를 실행

Shell 에 내장된 명령

Page 43: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 43

Exit n– n 값의 의미– exit 0 : 성공– exit 1 ~ 125 : 스크립트에서 사용 가능한 에러 코드 .– exit etc… : 예약된 코드 .

<ex> 126 : 파일이 실행 가능하지 않았다 . 127 : 명령이 발견되지 않았다 . 128 이상 : Signal 발생

Shell 에 내장된 명령

Page 44: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 44

printf– printf “ 형식 문자열” 매개변수 1 매개변수 2 …

printf 에서의 escape 문자 .

Shell 에 내장된 명령

Escape Sequence 설 명\\ 역슬래시 문자\a 경고 ( 벨이나 경고음을 울린다 )

\b 백스페이스 문자\f 폼 피드 문자\n 새 줄 문자\r 개행 문자\t 탭 문자\v 수직 탭 문자

\ooo 8 진수 값 ooo 를 가지는 한 문자

Page 45: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 45

printf 의 중요한 변환 지정자

Shell 에 내장된 명령

변환 지정자 설 명d 10 진수를 출력한다 .

c 문자를 출력한다 .

s 문자열 (string) 을 출력한다 .

% % 문자를 출력한다 .

Page 46: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 46

#/bin/bashy=1while [ $y -le 12 ]; do

x=1while [ $x -le 12 ]; do

printf "% 4d" $(( $x * $y ))let x++

doneecho ""let y++

done

#/bin/shy=1while [ $y -le 12 ]; do

x=1while [ $x -le 12 ]; do

printf "% 4d" $(( $x * $y ))x=$((x+1))

doneecho ""y=$((y+1))

done

Page 47: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 47

return– 함수 반환– 하나의 숫자 매개변수를 가진다 .

set– set 명령은 쉘을 위한 파라미터 변수를 설정

Shell 에 내장된 명령

Page 48: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 48

Shift– Shift 명령은 모든 파라미터 변수를 한 단계 아래로 이동

Shell 에 내장된 명령

[ue20@zeus ch2]$ vim shift.sh

#!/bin/shwhile [ “$1” != “” ]do

echo “$1”shift

doneexit 0

Page 49: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 49

다음 작업을 하는 shell program 을 작성한다 .

1. Creating 1000 files

$ ./create1000files.sh

- ~/test/ 디렉토리에 1.txt, 2.txt, …, 1000.txt 파일을 생성함 . 빈파일이 생성됨 .

참고 :

$ touch 1.c //1.c 파일이 생성됨 .

2. 임의의 실행파일이 설치되어있는 폴더를 echo 하는 프로그램 예 :

$ ./find.sh bash

/bin/

참고 : whereis bash 명령과 cut 명령 , echo 명령 , backtick 등을 사용하여 구현 가능 ( 파이프를 사용해서 한줄로도 가능 )

3. CPU 의 코어개수를 echo 하는 한줄 bash 스크립트 (/proc/cpuinfo 텍스트 파일 참고 )

Quiz

Page 50: SHELL programming - | calab.hanyang.ac.krcalab.hanyang.ac.kr/courses/SP_taesoo/prct_04_shell... · 2019-10-30 · Page 7 Shell Programming 두 가지 방법 – 명령을 차례(line

Page 50

Reference

KLDP Shell Programming 의 기본– http://wiki.kldp.org/wiki.php/DocbookSgml/Shell_Programming-TRANS

초보자용 Shell Programming– http://www.softintegration.com/docs/ch/shell/