While Loop
Part of the Fundamentals section of Coddy's Terminal journey — lesson 72 of 82.
The for loop is great when you know exactly what items to iterate through. But what if you want to keep looping until a certain condition changes? That's where the while loop comes in.
A while loop continues running as long as its condition remains true. Here's the basic structure:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
doneThis script prints numbers 1 through 5.
The loop checks if count is less than or equal to 5. If true, it runs the body, increments the counter using $((...)) for arithmetic, and checks again.
Once count reaches 6, the condition becomes false and the loop stops.
While loops are perfect when you don't know in advance how many iterations you need. For example, you might keep asking for input until the user types "quit":
#!/bin/bash
input=""
while [ "$input" != "quit" ]; do
read -p "Enter command (quit to exit): " input
echo "You entered: $input"
doneBe careful with while loops. If the condition never becomes false, your loop runs forever.
Always make sure something inside the loop eventually changes the condition, like incrementing a counter or updating a variable based on user input.
Challenge
EasyCreate a shell script called counter.sh that uses a while loop to print numbers from 1 to 4.
Your script should:
- Start with the shebang line (
#!/bin/bash) - Create a variable called
numwith the initial value1 - Use a while loop that continues as long as
numis less than or equal to 4 - Inside the loop, print the current number in the format:
Number: [num] - Increment
numby 1 after each iteration using$((num + 1))
Make the script executable and run it. Your output should be:
Number: 1
Number: 2
Number: 3
Number: 4Hint: Use
-lefor "less than or equal to" comparison. Remember to increment the counter inside the loop withnum=$((num + 1))to avoid an infinite loop. End your while loop withdone.
Cheat sheet
A while loop continues running as long as its condition remains true:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
doneThe loop checks the condition before each iteration. Use $((...)) for arithmetic operations to increment counters.
While loops are useful when you don't know in advance how many iterations you need, such as waiting for specific user input:
#!/bin/bash
input=""
while [ "$input" != "quit" ]; do
read -p "Enter command (quit to exit): " input
echo "You entered: $input"
doneAlways ensure something inside the loop eventually changes the condition to avoid infinite loops.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective10Log Analyzer Project
Project OverviewViewing The Log File13Shell Scripting Basics
What Is A Shell ScriptCreate And Run A ScriptVariables In ScriptsUser Input In ScriptsIf StatementFor LoopWhile LoopRecap - Number Guesser2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline