A do-while loop is a type of loop construct in programming languages that executes a block of code repeatedly until a certain condition is met. In Linux, the purpose of a do-while loop is to execute a certain set of commands repeatedly, based on a specific condition, until the condition is no longer true.
The syntax for a do-while loop in Linux is as follows:
do
command1
command2
...
commandN
while [ condition ];
Here, the commands within the do block are executed repeatedly until the condition specified in the while statement becomes false. The while statement is evaluated after each iteration of the loop.
One common use of a do-while loop in Linux is to implement a menu-driven interface, where the user is prompted to enter a choice and the program executes the corresponding action until the user chooses to exit the menu.
Overall, the purpose of a do-while loop in Linux is to provide a flexible and powerful way to automate repetitive tasks and implement interactive programs.
Example:
Create a file
touch do-while
Very important, you need to give execute permission to the file, in order to edit it
chmod u+x do-while
Now you can open the file, by using an editor
vi do-while
Add the following script
#!/bin/bash
count=0
num=10
while [ $count -lt 10 ]
do
echo
echo $num seconds left to stop this process $1
echo
sleep 1
num=`expr $num - 1`
count=`expr $count + 1`
done
echo
echo $1 process is stopped!!!
echo
This code is a Bash script that implements a countdown timer for stopping a process.
The first line, #!/bin/bash, specifies the interpreter to use, which is Bash in this case.
The script initializes two variables: count is set to 0, and num is set to 10.
The script then enters a while loop, which will execute repeatedly as long as the condition [ $count -lt 10 ] is true. This condition checks if the value of count is less than 10.
Within the loop, the script prints out a message to the console using the echo command. This message displays the value of the num variable, the string “seconds left to stop this process”, and the value of the first command-line argument passed to the script ($1).
The sleep command causes the script to pause for one second before executing the next iteration of the loop.
The script then updates the num and count variables by subtracting 1 from num and adding 1 to count.
When the condition of the while loop is no longer true, the script prints a message to the console indicating that the process has been stopped. This is done using two echo commands.
Overall, this script is a simple countdown timer that counts down from 10 to 1, printing a message to the console for each second, before finally indicating that the specified process has been stopped.