Shell - 9.Looping

참고 강의 : TTABAE-LEARN


Contents

  • 9-1. 산술 연산 expr, let
  • 9-2. while and until loop
  • 9-3. for-loop


9-1. 산술 연산 expr, let

expr

  • command로 다 가능

  • example

$ expr 10+5
$ expr 10-5
$ expr 10'*'5
$ expr 10'/'5
$ expr 10'%'3

$ x=5
$ expr $x>4
$ expr $x=8
$ sum=`expr $x+10`


let

  • bash shell안에 built in
  • 변수 앞에 $ 붙일 필요 없음
  • let 대신 두개의 (())를 사용해도 OK
    • 복습 : test는 []를 사용해도 OK
  • example
$ let sum=x+5
$ let x++ # x를 1만큼 증가시키기
$ let x+=1

$ ((sum=x+5))
$ ((x++))
$ ((x-=1))


9-2. while and until loop

example

while

$ cat while-exam.sh
num=1
while test $num -le 5
do
 echo Number: $num
 ((num++))
done
$ while-exam.sh
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5


until

$ cat > until-exam.sh
num=1
until test $num -gt 5
do 
 echo Number: $num
 ((num++))
done
$ until-exam.sh
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5


9-3. for-loop

example 1)

for NUM in 1 2 3 4 5 6
do 
 echo $NUM
done


example 2)

for NUM in $(seq 10)
do 
 echo $NUM
done


example 3)

fore file in *
do
 ls $file
done


example 4)

if [! -d ~/backup]
then
 mkdir ~/backup
fi

for FILE in *
do
 cp $FILE /backup/$FILE.old
done

Categories:

Updated: