You've hit on a great follow-up question! The continue statement is incredibly useful for optimizing loop performance and making your code cleaner by handling specific cases.
You would use continue when you are iterating through a list of items or a range, and for certain items, you want to skip the rest of the processing for that specific iteration and move directly to the next item in the loop.
Essentially, it's for cases where:
-
You have specific conditions under which processing for an item is not needed or valid. Instead of wrapping the entire rest of the loop's body in an
ifstatement,continueallows you to quickly filter out unwanted items at the top of the loop. -
You want to perform actions only on items that meet certain criteria.
continuehelps you skip over items that don't meet those criteria.
Common Scenarios for using continue:
-
Filtering Data: As seen in your example, skipping even numbers and only processing odd ones.
# Process only non-empty lines from a file while IFS= read -r line; do if [ -z "$line" ]; then # If line is empty continue # Skip to the next line fi echo "Processing non-empty line: $line" done < "my_data.txt" -
Skipping Invalid Inputs/Items: If you're processing a list of files, and some might not exist or don't have the correct extension.
# Only process .txt files and skip others for file in *; do if [[ ! "$file" =~ \.txt$ ]]; then # If file doesn't end with .txt echo "Skipping non-text file: $file" continue # Move to the next file fi echo "Processing text file: $file" # ... do something with the text file ... done -
Error Handling (for specific items): If an operation fails for a particular item, you might log the error and then
continueto try the next item, rather than exiting the entire loop.# Try to connect to a list of servers, skip if connection fails for one for server in server1 server2 server3; do if ! ping -c 1 "$server" &> /dev/null; then # If ping fails echo "Warning: Could not reach $server. Skipping." continue # Try the next server fi echo "Successfully connected to $server. Proceeding with tasks." # ... perform tasks on $server ... done
In summary, use continue when you want to bypass the rest of the current iteration's code for a specific reason, but still want the loop to proceed with its subsequent iterations. It helps in creating more efficient and readable loops by handling exceptions or filters upfront.
Does this elaborate a bit on the practical uses of continue for you?