Skip to content

Instantly share code, notes, and snippets.

@bhumit070
Created August 1, 2024 06:14
Show Gist options
  • Save bhumit070/6285ed8cdbadf82a36b1d40d8161f2fc to your computer and use it in GitHub Desktop.
Save bhumit070/6285ed8cdbadf82a36b1d40d8161f2fc to your computer and use it in GitHub Desktop.
All loops example in shell script
  • continue: Skips the rest of the current loop iteration and proceeds with the next iteration.
  • break: Exits the loop immediately.

Here are examples demonstrating the use of continue and break in each type of loop:

Using for loop:

#!/bin/bash

for file in "$PWD"/*
do
    if [[ $file == *".skip" ]]; then
        continue  # Skip files with ".skip" extension
    fi

    echo "Processing file: $file"

    if [[ $file == *".stop" ]]; then
        break  # Stop processing if file has ".stop" extension
    fi
done

Using C-style for loop:

#!/bin/bash

files=("$PWD"/*)
for ((i=0; i<${#files[@]}; i++))
do
    if [[ ${files[i]} == *".skip" ]]; then
        continue  # Skip files with ".skip" extension
    fi

    echo "Processing file: ${files[i]}"

    if [[ ${files[i]} == *".stop" ]]; then
        break  # Stop processing if file has ".stop" extension
    fi
done

Using while loop:

#!/bin/bash

files=("$PWD"/*)
i=0
while [ $i -lt ${#files[@]} ]
do
    if [[ ${files[i]} == *".skip" ]]; then
        ((i++))
        continue  # Skip files with ".skip" extension
    fi

    echo "Processing file: ${files[i]}"

    if [[ ${files[i]} == *".stop" ]]; then
        break  # Stop processing if file has ".stop" extension
    fi

    ((i++))
done

Using until loop:

#!/bin/bash

files=("$PWD"/*)
i=0
until [ $i -ge ${#files[@]} ]
do
    if [[ ${files[i]} == *".skip" ]]; then
        ((i++))
        continue  # Skip files with ".skip" extension
    fi

    echo "Processing file: ${files[i]}"

    if [[ ${files[i]} == *".stop" ]]; then
        break  # Stop processing if file has ".stop" extension
    fi

    ((i++))
done

Using select loop:

#!/bin/bash

select file in "$PWD"/*
do
    if [[ $file == *".skip" ]]; then
        continue  # Skip files with ".skip" extension
    fi

    echo "Processing file: $file"

    if [[ $file == *".stop" ]]; then
        break  # Stop processing if file has ".stop" extension
    fi
done

In these examples, the continue statement is used to skip processing files with the .skip extension, and the break statement is used to stop the loop if a file with the .stop extension is encountered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment