본문 바로가기
IT 지식정리/운영체제

[Linux shell script 2] 리눅스 쉘스크립트 "while" 2015. 1. 27.

by G. Hong 2017. 11. 4.
728x90
반응형

리눅스의 쉘스크립트에서 while을 사용하는 방법에 대해서 알아보도록 하겠습니다.


제 기억에 프로그래밍을 하였을 때, 가장 많이 사용하였던 명령어 중 하나가 while이 었던 것 같습니다.


한번 가장 간단한 while 문을 만들어 보겠습니다.

$ vi t001

#!/bin/bash

# sample script


n=0

while(($n<5))

do

 echo "hello $n"

 n=$((n+1))

done


출력 성공~!

$ ./t001

hello 0

hello 1

hello 2

hello 3

hello 4

$


bash script와 관련된 문서를 보니 while의 문법이 아래와 같다고 하네요.

while [ condition ]

do

command1

command2

commandN

 

done


()괄호 대신[]로 변경하여 사용해 보겠습니다. 그리고 <대신 -le를 사용해 보겠습니다.


$ cat t001

#!/bin/bash

# sample script


n=0

while[$n -le 5]

do

 echo "hello $n"

 n=$((n+1))

done

?!! 문법을 그대로 사용한 것 같은데, 에러가 발생합니다..

$ ./t001

./t001: line 5: while[0 -le 5]: command not found

./t001: line 6: syntax error near unexpected token `do'

./t001: line 6: `do'


혹시나 해서 []괄호 안의 내용을 ()괄호로 묶어 보았습니다.

$ cat t001

#!/bin/bash

# sample script


n=0

while[($n -le 5)]

do

 echo "hello $n"

 n=$((n+1))

done


역시 에러가 발생합니다.

$ ./t001

./t001: line 5: while[(0 -le 5)]: command not found

./t001: line 6: syntax error near unexpected token `do'

./t001: line 6: `do'


while뒤에 띄어쓰기를 넣고, 조건문에도 띄어쓰기를 넣어 보았습니다.

$ cat t001

#!/bin/bash

# sample script


n=0

while [ $n -le 5 ]

do

 echo "hello $n"

 n=$((n+1))

done


문제가 해결되었습니다..쉘 스크립트 조건문에서 띄어쓰기도 신경을 써야하는 부분이네요.. -le는 <= 와 동일하다고 보면 될 것 같습니다.

$ ./t001

hello 0

hello 1

hello 2

hello 3

hello 4

hello 5

 

$

728x90
반응형