linux 명령어 continue

루프 계속 하는 명령어.

$ continue
Linux 명령어 continue

Linux 명령어 continue

반복문에서 특정 조건에 따라 다음 반복으로 건너뛰는 명령어

1. 자세한 설명

continue 명령어는 Linux의 셸 스크립트에서 반복문 내에서 특정 조건이 만족될 경우 현재 반복의 남은 부분을 건너뛰고 다음 반복을 실행하도록 합니다. 주로 for, while, until과 같은 반복문에서 사용됩니다.

2. 사용법

  1. 조건 기반 반복 건너뛰기
    반복문 안에서 조건문과 함께 사용하여 특정 조건을 만족할 때 다음 반복으로 건너뜁니다.
  2. 중첩된 반복에서 사용
    중첩된 반복문에서 특정 반복을 건너뛰기 위해 continue [n]을 사용합니다. 여기서 n은 건너뛸 반복문의 레벨을 지정합니다.

3. 자세하게 설명

continue 명령어의 주요 특징:

  • 단순 반복 건너뛰기: 기본적으로 현재 반복의 남은 코드를 실행하지 않고 다음 반복으로 넘어갑니다.
  • 중첩 반복 처리: continue [레벨]을 사용하여 특정 수준의 반복문을 건너뛸 수 있습니다.
  • 조건과 함께 사용: if, case 등의 조건문과 함께 사용하여 유연한 흐름 제어가 가능합니다.

4. 자세한 명령어 사용법

다음은 continue 명령어의 다양한 사용 예제입니다:

# 기본 반복에서 조건 충족 시 건너뛰기
for i in {1..10}; do
  if [ $i -eq 5 ]; then
    continue
  fi
  echo "Number: $i"
done

# 특정 문자열 건너뛰기
names=("Alice" "Bob" "Charlie")
for name in "${names[@]}"; do
  if [ "$name" == "Bob" ]; then
    continue
  fi
  echo "Hello, $name!"
done

# 중첩된 반복에서 특정 레벨 건너뛰기
for i in {1..3}; do
  for j in {1..3}; do
    if [ $j -eq 2 ]; then
      continue 1
    fi
    echo "i=$i, j=$j"
  done
done

# while 반복문에서 사용
counter=0
while [ $counter -lt 5 ]; do
  counter=$((counter + 1))
  if [ $counter -eq 3 ]; then
    continue
  fi
  echo "Counter: $counter"
done

# 특정 조건 만족 시 다음 반복으로 이동
for i in {1..10}; do
  remainder=$((i % 2))
  if [ $remainder -eq 0 ]; then
    continue
  fi
  echo "$i is an odd number."
done

# until 반복문에서 사용
counter=0
until [ $counter -ge 5 ]; do
  counter=$((counter + 1))
  if [ $counter -eq 2 ]; then
    continue
  fi
  echo "Value: $counter"
done

# 함수 내에서 사용
function skip_value {
  for value in {1..5}; do
    if [ $value -eq 4 ]; then
      continue
    fi
    echo "Processing value: $value"
  done
}
skip_value

# 특정 파일 처리 건너뛰기
files=("file1.txt" "file2.log" "file3.txt")
for file in "${files[@]}"; do
  if [[ "$file" == *.log ]]; then
    continue
  fi
  echo "Processing: $file"
done

# 로그 파일에서 특정 라인만 출력
while read -r line; do
  if [[ $line == *"ERROR"* ]]; then
    continue
  fi
  echo "$line"
done < log.txt

# 스크립트를 통해 동적으로 조건 건너뛰기
#!/bin/bash
numbers=(1 2 3 4 5)
for num in "${numbers[@]}"; do
  [ $num -eq 3 ] && continue
  echo "Number is $num"
done
            

위의 예제는 continue 명령어를 사용하여 반복문 내에서 조건적으로 흐름을 제어하는 다양한 방법을 보여줍니다.

© 2025 Linux 명령어 설명

Categories:

No responses yet

답글 남기기