티스토리 뷰

IoT 과정

Program Loops

gaelim 2017. 7. 7. 10:49
반응형

Programs Loops

while condition
do commands
done

until condition
do commands
done

for "$variable" in argument_list
do commands
done


* if, while until 등에 들어가는 조건문 안에는 어떠한 커맨드 ls, more 또는 파이프라인을 이용한 cat /etc/passwd | grep "user" command를 써도된다. 왜냐하면 어떠한 커맨드도 리턴값을 가지고 있기 때문이다. 주로 쓰이는 커맨드가 패턴비교나 산술비교를 하는[[ ]] test, (( )) let 인 것을 생각해보자. 

The while Loop 

while command_is_true
do
...
done

Valid Syntax include

$ while true         // true return value is 0 in posix shell
$ while command // any shell command is fine, because any shell cmd returns value
$ while [[ test_condition ]]
$ while (( arithmetic_test ))
$ while $var                    // not recommended for use
$ while $(command)         // not recommended for use

While Loop 이동방식

0 while
1 command_is_true  , if true goto 2, if false goto 3
2 loop body  , goto 1
3 done


The until Loop

until command_is_true
do
...
done

Until Loop 이동방식

0 until
1 command_is_true  , if true goto 3, if false goto 2
2 loop body  , goto 1
3 done

* while과 until Loop은 서로 뒤집어 놓은 것과 같이 반대로 행동한다. 왜 사용되는지 생각해보면 while을 until Loop처럼 사용하기위해선 condition에서 단순한 패턴비교 산술비교인 test, let는 negation의 특수기호인 ! 를 넣기만 하면된다. 그러나 condition에는 복잡한 command line이 들어갈 수 있고 이것을 negation 시키기 쉽지 않으므로, until Loop 역할 또한 필요하다 고 생각 할 수 있다.


The for Loop

for var in argument_list
do
  (( var = var*2 ))
  print $var
done

사용의 예 

for file in mydir/a*
do
  chmod -x $file
done

for user in $(who | sort -u | tr -s ' ' | cut -f1 -d' ')
do
  ... 
done

for var in $(command)
do
 ...
done


Breaking Out of a Loop

do
  ...
  break  -------------------
  ...                             |
done                          |
next_command_line <----


break 구문은 바로 아래인 done 한개 아래의 커맨드 라인으로 이동한다. nested 된 반복문을 다 나가고 싶은경우 break 나갈 done 갯수를 break 뒤에 인자로 숫자를 줄 수 있다. break [#] // default 는 1이다.


continue Command

do  <--------------
  ...                   |
  continue --------
  ...
done

continue 구문을 바로 위 do 커맨드 라인으로 이동한다. nested 된 반복문인 경우 몇 개 위의 do에서 다시 시작할 건지 continue 뒤에 숫자 인자를 줄 수 있다. continue [#] // default 는 1이다. 


exit Command

exit 커맨드는 program return 값을 결정한다. 또한 커맨드 수행시 파일 수행을 종료한다. 파일에 exit 명령어를 줬을 때 default로 exit $? 를 수행하므로 exit 바로 위 커맨드의 true, false값을 리턴한다. exit [#] 로 return 값을 설정할 수 있다.


Select Loop

Select Loop는 인자로 받은 것들을 메뉴처럼 보여준다. 잘 안쓰지만 메뉴 보여줄 땐 효율적인것 같아 그냥 자료로 남긴다.


$ cat select2.sh

#!/usr/bin/sh

# select an argument from the command line

# arg list is processed as $@

# usage: select2.sh arg arg arg .


if (( $# == 0 ))

then

 print "usage:  $0 arg arg arg ."

 false

 exit

fi


PS3="Choose an item from the list:  "

select choice

do


  print "The value of REPLY is: $REPLY"


  print "The value of choice is: $choice"


done

exit



$ ./select2.sh hamburger kimchi beef noodle

1) hamburger

2) kimchi

3) beef

4) noodle

Choose an item from the list:  1

The value of REPLY is: 1

The value of choice is: hamburger

Choose an item from the list:  2

The value of REPLY is: 2

The value of choice is: kimchi

Choose an item from the list:  3

The value of REPLY is: 3

The value of choice is: beef

Choose an item from the list:  4

The value of REPLY is: 4

The value of choice is: noodle


실습 - 입출력 pipe, 키보드 buffer


$ vi ex10.sh

"ex10.sh" 19 lines, 414 characters

     1  #! /usr/bin/sh
     2
     3  # This script use the while loop and creates a list of all of the
     4  # file systems on the current machine and the current percent used.
     5  # You should extract data from the bdf command
     6  # display only the items that are greater than 20 percent full
     7
     8  typeset -i i=0
     9
    10  bdf | while read data
    11  do
    12  set $data
    13  if [[ "$1" = "Filesystem" ]]
    14  then continue
    15  fi
    16  if (( "${5%\%}" > 20 ))
    17  then print "$1 \t $5 "
    18  fi
    19  done


bdf 는 여러 줄에 걸쳐 시스템 정보를 출력한 것을 버퍼에 남긴다. while 문이 실행되면서 조건문에 있는 read가 수행되는데 read cmd는 버퍼에 있는 것을 line by line으로 들고와 변수 data에 저장한다. 즉 첫 줄은 카테고리 이름일 것이다. 그리고 set cmd는 set $var_name 를 통해 공백 사이로 내용을 끊어 번호를 매길 수 있게 해준다.


반응형

'IoT 과정' 카테고리의 다른 글

Functions and Function Libraries  (0) 2017.07.07
Array Variable  (0) 2017.07.07
Shell Patterns  (0) 2017.07.07
Branches and Logic Testing  (0) 2017.07.06
Shell Arithmetic  (0) 2017.07.06