Bash shell script에서 무한 루프(Infinite loop)를 만드는 방법들을 소개합니다.
Example 1 : while loop
다음과 같이 while을 이용하여 무한 루프를 만들 수 있습니다. if와 break를 이용하여 특정 조건에서 루프를 탈출하도록 구현할 수도 있습니다.
#!/bin/bash
while :
do
echo "Doing something"
sleep 1
done
Output:
$ bash example.sh
Doing something
Doing something
Doing something
Doing something
...
Example 2 : while loop
아래 예제도 무한 루프이고, 위의 예제와 거의 동일합니다. while :
대신에 while true
를 사용하였습니다.
#!/bin/bash
while true
do
echo "Doing something"
sleep 1
done
Output:
$ bash example.sh
Doing something
Doing something
Doing something
Doing something
...
Example 3 : for loop
아래 예제는 for
를 이용하여 무한 루프를 구현하였습니다. for의 탈출 조건을 생략하여 무한 루프를 만들었습니다.
#!/bin/bash
for (( ; ; ))
do
echo "Doing something"
sleep 1
done
Output:
$ bash example.sh
Doing something
Doing something
Doing something
Doing something
...
Example 4 : Single line
아래 예제는 1줄로 무한 루프를 만드는 방법입니다. Script 뿐만 아니라, 터미널에서도 간편히 사용할 수 있습니다.
#!/bin/bash
while true; do echo "Doing something"; sleep 1; echo "Doing other things"; done
Output:
$ bash example.sh
Doing something
Doing other things
Doing something
Doing other things
Doing something
Doing other things
...
Loading script...
Related Posts
- Bash Shell - 실행 시간 측정 방법
- Bash Shell - 나눗셈에서 버림, 올림, 반올림 처리
- Bash Shell - 숫자가 양수인지 음수인지 확인하는 방법
- Bash Shell - 자신의 스크립트 파일 이름 가져오기
- Bash Shell - 문자열 출력 방법(echo, printf)
- Bash Shell - seq 명령어로 반복문 구현 및 예제
- Bash Shell - File 테스트 연산자
- Bash Shell - 무한 루프 (Infinite loop)
- Bash Shell - 숫자 비교 연산자
- Bash Shell - 문자열 비교 연산자
- Bash Shell - 대문자, 소문자로 변환 (Uppercase, Lowercase)
- Bash Shell - 스트립트를 root로 실행했는지 확인
- Bash Shell - 명령어 실행 결과를 변수에 저장
- Bash Shell - select로 선택 메뉴 구현
- Bash Shell - 변수가 정의되었는지 확인하는 방법
- Bash Shell - sleep 함수, 특정 시간 멈추기
- Bash Shell - 파일이 존재하는지 확인
- Bash Shell - 문자열 자르기 (substring, split)
- Bash Shell - 날짜, 시간 가져오기
- Bash Shell - Case 조건문
- Bash Shell - 파일 읽는 방법