C.W.K.
Stream
Lesson 04 of 12 · published

반복문 — for, while, until

~12 min · for, while, until, loops

Level 0창 구경꾼
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

for — 목록 순회

for f in *.txt; do
  echo "processing $f"
done

목록은 무엇이든: glob 결과, 명시 목록, command substitution, 배열.

for — 범위

# C 스타일 (bash/zsh)
for ((i=0; i<10; i++)); do echo $i; done
# brace expansion
for i in {1..10}; do echo $i; done
for i in {1..10..2}; do echo $i; done   # step

for — 배열

files=("a.txt" "b.txt" "c.txt")
for f in "${files[@]}"; do echo "$f"; done

"${arr[@]}" 가 원소당 quoted token 하나씩 펼침. "${arr[*]}" 는 IFS 로 합쳐 하나의 문자열 — 거의 항상 잘못.

while

i=0
while [[ $i -lt 5 ]]; do
  echo $i
  ((i++))
done

# 파일을 줄 단위로 읽기
while IFS= read -r line; do
  echo "> $line"
done < input.txt

IFS= read -r 가 안전 형 — 앞뒤 공백, backslash 보존. 모든 줄별 파일 읽기에.

until — while 의 역

until ping -c1 server.local; do
  echo 'waiting...'
  sleep 5
done

break / continue

break 가 현재 루프 종료. break 2 는 중첩 두 단계 종료. continue 는 다음 iteration 으로 건너뜀.

Code

파일을 줄 단위로·bash
while IFS= read -r line; do
  [[ -z "$line" || "$line" == \#* ]] && continue
  echo "config: $line"
done < ~/.config/myapp.conf

External links

Exercise

주석과 빈 줄 빼고 .zshrc 의 모든 설정 줄 나열하는 루프: while IFS= read -r l; do [[ -z "$l" || "$l" == \#* ]] && continue; echo "$l"; done < ~/.zshrc.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.