111 Dowhile in Shell Scripting
Автор: Engineering Academy Online
Загружено: 2024-10-20
Просмотров: 6
Описание:
In shell scripting, a do...while loop allows you to execute a block of commands repeatedly as long as a specified condition is true. Unlike a regular while loop, the do...while loop guarantees that the block of code will run at least once, since the condition is checked after the execution of the loop body.
Syntax
Here's the basic syntax for a do...while loop in a shell script:
bash
Copy code
#!/bin/bash
Initial setup (optional)
counter=1
Do-While loop
do
Commands to execute
echo "Counter is: $counter"
Increment or modify the counter
((counter++))
Condition to evaluate (after the block)
done while [ $counter -le 5 ]
Explanation
Initialization: You can initialize variables before the loop starts.
do: This keyword marks the beginning of the loop's body.
Commands: You can place any commands you want to execute inside the loop.
done: This keyword marks the end of the loop.
while [ condition ]: The condition is checked after the commands are executed. If it evaluates to true, the loop will continue.
Example
Here’s an example that reads numbers until the user enters a zero:
bash
Copy code
#!/bin/bash
Variable initialization
number=1
Do-While loop
do
read -p "Enter a number (0 to exit): " number
echo "You entered: $number"
done while [ $number -ne 0 ]
echo "Exited the loop."
Key Points
The do...while loop ensures the body executes at least once.
Useful for scenarios where you need user input or when the loop's execution depends on the result of commands run inside the loop.
Make sure to update your condition within the loop to avoid infinite loops.
This structure is quite handy for interactive scripts and scenarios where the condition might be determined by user input or the result of processing data.
Повторяем попытку...

Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: