FUNDAMENTALS A Complete Guide for Beginners
Continue statement in bash while loop skips the current iteration and jumps to the next iteration. It is a control statement that allows programmers to skip any specific iterations during loop execution. In this article, I will explore the process of using the continue statement in a while loop.
7 Examples of “while” Loop with Continue Statement
While loop with continue statement in Bash can print a series of numbers considering user input or specific choice, process a specific type of files. Here, I will demonstrate 7 examples of these.
1. Skipping Iteration with Continue Statement in “while” Loop
While loop executes the commands inside the block as long as the condition is true. Use the continue statement with while loop in Bash to skip any iteration. Here is a bash script to print numbers from 0 to 5, skipping 2:
#!/bin/bash
a=0
while [[ $a -lt 5 ]]; do
((a++))
if [[ "$a" == '2' ]]; then
continue
fi
echo "Number: $a"
done
echo "Done!"
while [[ $a -lt 5 ]];
initiates a while loop that iterates as long as the value of a is less than 5. Then ((a++))
increases the value of a by one. The if [[ "$a" == '2' ]];
checks whether the value of a is equal to 2. If yes, then it skips the current iteration and jumps to the next iteration. Otherwise, it prints the value of a with the echo command.
2. Finding Even Numbers
Even numbers are those numbers whose remainder after dividing by 2 is zero. While loop iterates as long as the loop condition is true. Keeping the logic inside the if clause inside the loop, even numbers can easily be determined. Here is a bash script to find even numbers from an iteration list:
#!/bin/bash
a=1
while [ $a -le 10 ]; do
if [ $((a % 2)) -eq 1 ]; then
#Skip odd numbers
a=$((a + 1))
continue
fi
echo $a
a=$((a + 1))
done
while [ $a -le 10 ];
initiates a while loop that iterates as long as the value of a is less than 10. After that, if [ $((a % 2)) -eq 1 ];
checks whether the remainder after dividing a by 2 is equal to 1. If so, it will skip the iteration and jump to the next iteration. Otherwise, it will print that value of a, which is an even number.
3. Skipping a Specific Type of File
While loop can iterate through all files inside a directory. Keeping a specific condition inside the if statement of the loop enables programmers to skip a specific type of file. Here is a bash script that prints all the files inside the directory except txt files:
#!/bin/bash
dir="/home/susmit/Backup"
counter=1
while [ $counter -le "$(ls -1 "$dir" | wc -l)" ]; do
file=$(ls -1 "$dir" | sed -n "${counter}p")
if [ "${file##*.}" == "txt" ]; then
((counter++))
continue
fi
echo "$dir/$file"
((counter++))
done
while [ $counter -le "$(ls -1 "$dir" | wc -l)" ];
initiates a while loop that iterates as long as the counter is less than or equal to the number of files in the /home/susmit/Backup directory. Here, ls -1 "$dir" | wc -l
counts the number of files in the directory. file=$(ls -1 "$dir" | sed -n "${counter}p")
retrieves the name of the current file using ls -1 to list files in one column and sed -n "${counter}p"
selects the file at the current position indicated by the counter.
Then if [ "${file##*.}" == "txt" ];
checks whether the current iteration entity is a txt file. If so, it will skip the current iteration and jump to the next iteration. Otherwise, it will print the full path of the file.
4. Skipping Empty Lines in a File
While loop can iterate through a large file line by line. Skipping empty lines while printing file content on the terminal eases users’ task of going through files effectively. Here is a bash script that iterates through each line of a file and prints them, skipping the empty lines:
#!/bin/bash
while IFS= read -r line; do
if [ -z "$line" ]; then
continue
fi
echo "Processing line: $line"
done < "input.txt"
while IFS= read -r line;
initiates a while loop that reads each line from the input.txt file. Here, IFS= read -r line
reads a line from the file and assigns it to the variable ‘line’. The ‘IFS=’ part ensures the inclusion of leading and trailing whitespaces in the line, and the ‘-r’ option prevents backslashes from being treated as escape characters. The if [ -z "$line" ];
checks whether the line is empty. If so, it will skip the current iteration. Otherwise, it will print the line on the terminal.
5. Skipping Iteration Based on User Input
While loop can print a series of numbers considering the input from users while iterating. The read command can read user input and then incorporate the input inside the condition of the if statement, which can decide what to print and what not to print. Here is how to do this:
#!/bin/bash
c=1
while [ $c -le 5 ]; do
read -p "Do you want to accept $c? (y/n): " choice
if [ "$choice" == "n" ]; then
((c++))
continue
fi
echo "$c"
((c++))
done
while [ $c -le 5 ];
initiates a while loop that iterates as long ase the value of c is less than or equal to 5. Then read -p "Do you want to accept $c? (y/n): "
choice asks for input from the users and stores the user input into the choice variable. if [ "$choice" == "n" ];
checks whether the value of choice is n. If so, it will skip the current iteration and jump to the next iteration. Otherwise, it will print the current value of c.
6. Skipping Specific Values in an Array
While loop can iterate through an array with the help of an array index. Put the specified condition inside the condition block of the if statement to skip a specific element of an array. Here is a bash script that will print all the array elements except “Mike”:
#!/bin/bash
index=0
val=("Wade" "Warner" "Mike" "Lee")
while [ $index -lt ${#val[@]} ];do
current_val="${val[$index]}"
if [ "$current_val" == "Mike" ]; then
((index++))
continue
fi
echo "$current_val"
((index++))
done
while [ $index -lt ${#val[@]} ];
initiates a while loop as long as the index is less than the length of the val array. Then if [ "$current_val" == "Mike" ];
checks whether the value of current_val is “Mike”. If so, it will skip the current iteration and jump to the next iteration. Otherwise, it will print the current_val.
7. Concurrent Image Conversion
While loop in Bash can iterate through a list of photos with the help of array indexing, then, convert the image format from JPEG to PNG using the convert command. Here is a bash script where while loop will iterate over all JPEG files inside the current directory and convert them to PNG format:
#!/bin/bash
echo "Converting JPEG files to PNG concurrently:"
convert_image() {
local image="$1"
echo "Converting: $image"
convert "$image" "${image%.jpg}.png"
}
image_list=(*.jpg)
total_images=${#image_list[@]}
counter=0
while [ $counter -lt $total_images ]; do
current_image="${image_list[$counter]}"
convert_image "$current_image" &
counter=$((counter + 1))
done
wait
echo "Conversion complete."
The convert_image()
defines a function where the convert command performs the conversion task. Here, image_list=(*.jpg)
lists all the jpg files inside the image_list
variable and total_images= ${#image_list[@]}
finds the length of the “image_list” array.
After that, while [ $counter -lt $total_images ];
initiates a while loop that iterates as long as the value of the counter is less than the length of the total_images variable. Finally, convert_image "$current_image"
passes the current_image to the convert_image function to convert it to a PNG file.
Printing a Series of Numbers Then Exit
While loop can print a series of numbers, and it can be terminated with the break command. Here is a bash script that prints numbers from 0 to 3 and then terminates:
#!/bin/bash
a=0
while [[ $a -lt 5 ]]
do
echo "Value: $a"
((a++))
if [[ $a -eq 3 ]]; then
break
fi
done
echo "Done!"
while [[ $a -lt 5 ]]
initiates a bash while loop that will iterate as long as a is less than 5. Then if [[ $a -eq 3 ]];
checks whether the value of a is equal to 3. If so, it will terminate the while loop with the break command.
Conclusion
In conclusion, using the continue command in the bash while loop will make the bash script more versatile while iterating. It will give the control over which iteration entity to process and which to skip. This article will help the learners to use the continue statement in the while loop effectively.
People Also Ask
What does continue in Bash do?
The continue command in bash skips the current iterations and jumps to the next iteration. It does not execute the subsequent commands after the continue statement and jumps to the next iteration.
How do you break out of a while loop in Bash?
To break out of a while loop in Bash, use the break command. It will terminate the loop and go to subsequent commands after the loop. The break command is a control statement that allows the termination of a loop prematurely.
What is the difference between break and continue in Bash script?
The break command and the continue command are both control statements. The continue statement skips the current iteration and jumps to the next iteration without executing the commands after the continue statement. On the other hand, the break statement terminates loop execution and jumps to the subsequent command after the loop.
Can a while loop have multiple conditions?
Yes, a while loop can have multiple conditions. You could use logical AND (&&), OR (||) to combine multiple conditions inside the condition block of a while loop.
Related Articles
- “while true” Loop in Bash [4 Cases]
- 8 Examples of “while” Loop in Bash
- How to Read File Line Using Bash “while” Loop [8 Cases]
- How to Increment Number Using Bash “while” Loop [8 Methods]
- One Line Infinite “while” Loop in Bash [4 Examples]
- Exit “while” Loop Using “break” Statement in Bash [11 Examples]
- How to Use Bash One Line “while” Loop [8 Examples]
- How to Use “sleep” Command in Bash “while” Loop [6 Examples]
<< Go Back to “while” Loop in Bash | Loops in Bash | Bash Scripting Tutorial