Skip to content

002-bash-while-loop

A while loop in Bash can be used to read input from stdin (standard input), often using the read command inside the loop. This allows you to process user input or pipe data into the loop.

Example 1: Simple while loop to read from stdin

This loop reads each line of input until the end of the input (e.g., when the user presses Ctrl+D to signal the end of input).

while IFS= read -r line
do
    echo "You entered: $line"
done

Explanation: - IFS= read -r line: This reads a line from stdin, storing it in the variable line. The IFS (Internal Field Separator) is set to nothing to preserve leading and trailing spaces. The -r option ensures backslashes are not treated as escape characters. - The loop continues until the user ends the input (by pressing Ctrl+D or when the input stream ends).

Example 2: Reading user input interactively

You can also use this in an interactive script, where the user is prompted for input:

echo "Enter something (Ctrl+D to quit):"
while IFS= read -r line
do
    echo "You entered: $line"
done

Example 3: Reading from stdin with a condition

If you want to stop reading input based on a condition (e.g., the user types "exit"), you can use a conditional statement inside the loop:

echo "Enter some text (type 'exit' to quit):"
while IFS= read -r line
do
    if [ "$line" == "exit" ]; then
        echo "Exiting..."
        break
    fi
    echo "You entered: $line"
done

Example 4: Piping data into a while loop

You can also pipe data into a while loop. For example, let's use echo to send multiple lines of text into the loop:

echo -e "Line 1\nLine 2\nLine 3" | while IFS= read -r line
do
    echo "Read from pipe: $line"
done

Output:

Read from pipe: Line 1
Read from pipe: Line 2
Read from pipe: Line 3

Example 5: Reading input and processing each line with a command

You can read lines of input and process them using a command or script. Here's an example where we read each line and count the number of words in each line:

echo "Enter some text (Ctrl+D to quit):"
while IFS= read -r line
do
    word_count=$(echo "$line" | wc -w)
    echo "Word count: $word_count"
done

This will output the number of words for each line entered by the user.

Let me know if you need more examples or a specific case!