posted by 귀염둥이채원 2021. 4. 15. 10:25

 

---------------------------------------------------------

# Syntax of while loop:

---------------------------------------------------------

while [ condition ]; do

commands

done

 

---------------------------------------------------------

# 고정 횟수만큼 반복

---------------------------------------------------------

#!/bin/bash

n=1

while [ $n -le 5 ]; do

echo "Running $n time"

((n++))

done

 

# output

$ bash test.sh

Running 1 time

Running 2 time

Running 3 time

Running 4 time

Running 5 time

 

---------------------------------------------------------

# while에서 break 사용

---------------------------------------------------------

#!/bin/bash

n=1

while [ $n -le 10 ]; do

if [ $n == 6 ]; then

echo "terminated"

break

fi

echo "Position: $n"

((n++))

done

 

# output

$ bash test.sh

Position: 1

Position: 2

Position: 3

Position: 4

Position: 5

terminated

 

---------------------------------------------------------

# while에서 continue 사용

---------------------------------------------------------

#!/bin/bash

n=0

while [ $n -le 5 ]; do

((n++))

 

if [ $n == 3 ]; then

continue

fi

echo "Position: $n"

 

done

 

# output

$ bash test.sh

Position: 1

Position: 2

Position: 4

Position: 5

Position: 6

 

---------------------------------------------------------

# 무한루프

---------------------------------------------------------

#!/bin/bash

n=1

while :; do

printf "The current value of n=$n\n"

if [ $n == 3 ]; then

echo "good"

elif [ $n == 5 ]; then

echo "bad"

elif [ $n == 7 ]; then

echo "ugly"

elif [ $n == 10 ]; then

exit 0

fi

((n++))

done

 

# output

$ bash test.sh

The current value of n=1

The current value of n=2

The current value of n=3

good

The current value of n=4

The current value of n=5

bad

The current value of n=6

The current value of n=7

ugly

The current value of n=8

The current value of n=9

The current value of n=10