리눅스/Bash Shell 스크립트
[CentOS 7] 리눅스 배시 셸 (bash Shell) for 반복문, while 반복문
안산드레아스
2021. 3. 14. 14:27
반응형
반복문 형식
for 반복변수 in 값1 값2 값3 ...
do
반복구문
done
<< 간단 예시 10번 반복 >>
in 뒤에 숫자를 입력하는 방법.
in 뒤에 { 시작숫자 .. 끝숫자 } 을 이용하는 방법.
#!/bin/sh
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "value is ${i}"
done
for i in {1..10}
do
echo "value is ${i}"
done
exit 0
<< 특정 값만큼 증가 반복 >>
in 뒤에 {시작값..끝값..증가값}
#!/bin/sh
for i in {1..20..2}
do
echo "value is ${i}"
done
exit 0
<< 리스트(List) 내부 인자를 반복 >>
#!/bin/sh
list="2 4 6 8 10"
for i in ${list}
do
echo "value is ${i}"
done
exit 0
*주의점 in 뒤에를 "2 4 6 8 10" 으로 넣으면 하나의 문자열로 간주
<< 특정 디렉터리 파일 모두 출력 >>
#!/bin/sh
for files in /root/*
do
echo ${files}
done
exit 0
C언어 처럼 사용하기
<< C언어 처럼 반복문 >>
#!/bin/sh
for ((i=0; i<5; i++));
do
echo "value is ${i}"
done
exit 0
<< 무한 반복문 >>
#!/bin/sh
for (( ; ; ));
do
echo "infinite loops till you hit the \"ctrl+C\" buttom"
done
exit 0
기타 등등 for문에 대해서 더 자세한 내용은 아래 블로거님 참고
[리눅스 / 유닉스 / 셸 프로그래밍 ] 반복문 for문 루프(loop)! 문법, 활용예제, 같이 쓰면 좋은 구문,
[ Linux / Unix / Shell programming INDEX ] 안녕하세요~~ㅎㅎ 오늘은 반복문 중 for문에 대해서 포스팅을 이어가보도록 하겠습니다. ▼참고 배시 말고 일반 프로그래밍(C, C++ JAVA)에서 for문의 포스팅 [C, C+..
jhnyang.tistory.com
================================
while문 사용하기 (조건이 맞을 때까지 반복)
<< 무한 반복문 >>
*주의점, [ ] 사이에는 반드시 공백이 필요
#!/bin/sh
while [ 1 ]
do
echo "infinite loops till you hit the \"ctrl+C\" buttom"
done
exit 0
<< i 가 10보다 작을 때까지 반복 >>
1씩 증가하면서 계속 합을 더해 나감
#!/bin/sh
hap=0
i=1
while [ ${i} -le 10 ]
do
hap=`expr ${hap} + ${i}`
i=`expr ${i} + 1`
done
echo "total SUM value : ${hap}"
exit 0
<< pw맞을때까지 반복 >>
#!/bin/sh
echo "plz enter you pw"
read pw
while [ ${pw} != "1234" ]
do
echo "Wrong pw"
read pw
done
echo "logged in"
exit 0
반응형