티스토리 뷰

시스템 서버

[linux] Shell Script 공부 3일차 - Chapter 3

달리는개발자 2011. 10. 25. 17:41
Chapter 3 | Shell Structured Language Constructs

※ 리눅스 쉘 값
Zero Value(0) 는 Yes/True
NON-ZERO Value 는 No/False

$ cat foo
$ echo $?


foo 파일이 있는 경우 zero(0)가 반환된다.

$ cat > showfile
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi


$ chmod 755 showfile
$ ./showfile foo


다음 스크립트는 숫자가 양수인지 알아낸다.
$ cat > ispositive
#!/bin/sh
#
# Script to see whether argument is positive
#
if test $1 -gt 0
then
echo "$1 number is positive"
fi

$ chmod 755 ispostive
$ ispositive 5
5 number is positive
$ ispositive -45
아무것도 출력되지 않는다.
$is positive
./ispositive: test: -gt: unary operator expected


수학 연산자
쉘 스크립트 내의 수학 연산자 의미  일반 연산문 For test
statement with
if command
For [ expr ]
statement with
if command 
 -eq is equal to  5 == 6  if test 5 -eq 6  if [ 5 -eq 6 ] 
 -ne is not equal to 5 != 6 if test 5 -ne 6 if [ 5 -ne 6 ]
 -lt is less than 5 < 6 if test 5 -lt 6  if [ 5 -lt 6 ] 
 -le is less than or equal to   5 <= 6 if test 5 -le 6   if [ 5 -le 6 ]  
 -gt  is greater than  5 > 6  if test 5 -gt 6  if [ 5 -gt 6 ]
 -ge  is greater than or equal to   5 >= 6  if test 5 -ge 6  if [ 5 -ge 6 ]

문자 비교
연산자 의미 
 string1 = string2 string1은 string2와 같다 
string1 != string2  string1은 string2와 같지 않다 
 string1 string1은 NULL이 아니거나 정의되지 않았다
-n string1  string1은 NULL이 아니고 존재한다. 
 -z string1 string1은 NULL 이고 존재한다. 

파일 그리고 디렉토리 종류
 Test 의미 
-s file  빈 파일이 아니다 
-f file 파일이 존재하거나 디렉토리가 아닌 일반파일
 -d dir  디렉토리가 존재하고 파일이 아니다
 -w file 쓰기 가능한 파일 
 -r file 읽기 전용 파일 
 -x file 실행가능한 파일 

논리 연산자
연산자 의미 
 ! expression Logical NOT 
 expression1 -a expression2 Logincal AND 
 expression1 -o expression2 Logical OR 

if...else...fi
구문
   if condition
   then
      condition is zero (true - 0)
      execute all commands up to else statement
   else
      if condition is not true then
      execute all commands up to fi
   fi

예제
$vi isnump_n
#!/bin/sh
#
# Script to see whether argument is positive or negative
#
if [ $# -eq 0 ] 
then 
   echo "$0 : You must give/supply one integers" 
   exit 1
fi 
if test $1 -gt 0
then
   echo "$1 number is positive" 
else 
   echo "$1 number is negative"
fi

$ chmod 755 isnump_n
$ isnump_n 5
5 number is positive
$ isnump_n -45
-45 number is negative
$ isnump_n
./ispos_n : You must give/supply one integers
$ isnump_n 0
0 number is negative


if test $1 -ge 0
0과 같거나 크면 true

Nested if-else-fi

$ vi nestedif.sh
#!/bin/sh
osch=0
 
echo "1. Unix (Sun Os)"
echo "2. Linux (Red Hat)"
echo -n "Select your os choice [1 or 2]? "
read osch
 
if [ $osch -eq 1 ] ; then
     echo "You Pick up Unix (Sun Os)"
else #### nested if i.e. if within if ######
         
       if [ $osch -eq 2 ] ; then
             echo "You Pick up Linux (Red Hat)"
       else
             echo "What you don't like Unix/Linux OS."
       fi
fi


$ chmod +x nestedif.sh
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 1
You Pick up Unix (Sun Os)
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 2
You Pick up Linux (Red Hat)  Linux Shell Script Tutorial
$ ./nestedif.sh
1. Unix (Sun Os)
2. Linux (Red Hat)
Select you os choice [1 or 2]? 3
What you don't like Unix/Linux OS.


Multilevel if-then-else
구문
if condition
then
   condition is zero (true - 0)
   execute all commands up to elif statement
elif condition1
then
   condition1 is zero (true - 0)
   execute all commands up to elif statement
elif condition2
then
   condition2 is zero (true - 0)
   execute all commands up to else statement
else
   None of the above condition, condition1, condition2 are ture
   (i.e.-즉 all of the above nonzero or false)
    execute all commands up to fi statement

예제
$ cat > elf
#
#!/bin/sh
# Script to test if..elif...else
#
if [ $1 -gt 0 ]; then
  echo "$1 is positive"
elif [ $1 -lt 0 ]
then
  echo "$1 is negative"
elif [ $1 -eq 0 ]
then
  echo "$1 is zero"
else
  echo "Opps! $1 is not number, give number"
fi


$ chmod 755 elf
$ ./elf 1
$ ./elf -2
$ ./elf 0
$ ./elf a
Here o/p for last sample run:
./elf: [: -gt: unary operator expected
./elf: [: -lt: unary operator expected
./elf: [: -eq: unary operator expected
Opps! a is not number, give number


쉘 스크립트 반복문
컴퓨터는 특정 명령을 조건이 만족할 때까지 반복할 수 있다.
반복되는 명령의 집합을 loop라고 부른다
Bash는 다음과 같은 반복문을 제공한다.
- for loop
- while loop

a) 반복문에 사용되는 변수는 반드시 초기화되고 실행되야 한다.
b) 조건은 반복의 처음에 만들어진다.
c) The body of loop ends with a statement that modifies the value of the test (condition)
variable.

for Loop
구문
for { variable name } in { list }
do
   list가 끝날 때까지 각 아이템 하나 하나를 실행한다.(do done 사이의 문장을 반복)
done

예제1
$ cat > testfor
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done


$ chmod +x testfor
$ ./testfor


예제2
$ cat > mtable
#!/bin/sh
#
#Script to test for loop
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo "Use to print multiplication table for given number"
exit 1
fi
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done

$ chmod 755 mtable
$ ./mtable 7
$ ./mtable

7 * 1 = 7
7 * 2 = 14
...
..
7 * 10 = 70

Error - Number missing form command line argument
Syntax : ./mtable number
Use to print multiplication table for given numbe


구문2
for(( expr1; expr2; expr3 ))
do
   expr2가 true 일 떄까지 do done 사이 문장을 반복
done

예제
$ cat > for2
for ((  i = 0 ;  i <= 5;  i++  ))
do
  echo "Welcome $i times"
done


$ chmod +x for2
$ ./for2

Welcome 0 times
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

Nesting of for Loop

예제
$ vi nestedfor.sh
#!/bin/sh
for (( i = 1; i <= 5; i++ ))      ### Outer for loop ###
do
 
    for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ###
    do
          echo -n "$i "
    done
 
  echo "" #### print the new line ###
 
done

$ chmod +x nestedfor.sh
$ ./nestefor.sh
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

예제(체스판)
$ vi chessboard
#!/bin/sh
for (( i = 1; i <= 9; i++ )) ### Outer for loop ###
do
   for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ###
   do
        tot=`expr $i + $j`
        tmp=`expr $tot % 2`
        if [ $tmp -eq 0 ]; then
            echo -e -n "\033[47m "
        else
            echo -e -n "\033[40m "
        fi
  done
 echo -e -n "\033[40m" #### set back background colour to black
 echo "" #### print the new line ###
done

$ chmod +x chessboard
$ ./chessboard

while loop
구문
while [ condition ]
do
   command1
   command2
   command3
   ...
done

예제
$cat > nt1
#!/bin/sh
#
#Script to test while statement
#
#
if [ $# -eq 0 ]
then
   echo "Error - Number missing form command line argument"
   echo "Syntax : $0 number"
   echo " Use to print multiplication table for given number"
exit 1
fi
n=$1
i=1
while [ $i -le 10 ]
do
  echo "$n * $i = `expr $i \* $n`"
  i=`expr $i + 1`
done


$ chmod 755 nt1
$ ./nt1 7


The case Statement
다중 if문을 대체하기에 좋다.

구문
case $variable-name in
   pattern1) command
                ...
                command;;
   pattern2) command
                ...
                command;;
   patternN) command
                 ...
                command;;
             *) command
                 ...
                command;;
esac

예제
$ cat > car
#!/bin/sh
#
# if no vehicle name is given
# i.e. -z $1 is defined and it is NULL
#
# if no command line arg 
if [ -z $1 ]
then
  rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as rental
  rental=$1
fi
case $rental in
   "car") echo "For $rental Rs.20 per k/m";;
   "van") echo "For $rental Rs.10 per k/m";;
   "jeep") echo "For $rental Rs.5 per k/m";;
   "bicycle") echo "For $rental 20 paisa per k/m";;
   *) echo "Sorry, I can not gat a $rental for you";;
esac


CTRL + D로 저장 후 실행

$ chmod +x card
$ car van
$ car car
$ car Maruti-800


쉘 스크립트를 어떻게 디버깅 할까?
sh 나 bash 명령 시 -v -x option을 통해 해결함.

구문
sh option { shell-script-name }
or
bash option { shell-script-name }

option은 다음과 같다.
-v 읽은 라인을 출력
-x 인수값들이 대입되어 출력

예제
$ cat > dsh1.sh
#
# Script to show debug of shell
#
tot=`expr $1 + $2`
echo $tot

[root@shuiky ~]# sh -x dsh1.sh 4 5
++ expr 4 + 5
+ tot=9
+ echo 9
9
[root@shuiky ~]# sh -v dsh1.sh 4 5
#!/bin/sh
#
# Script to show debug of shell
#
tot=`expr $1 + $2`
expr $1 + $2
echo $tot
9

[root@shuiky ~]# sh -v -x dsh1.sh 4 5
#!/bin/sh
#
# Script to show debug of shell
#
tot=`expr $1 + $2`
expr $1 + $2
++ expr 4 + 5
+ tot=9
echo $tot
+ echo 9
9



반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함