Linux while process running

Syntax for a single-line while loop in Bash

I am having trouble coming up with the right combination of semicolons and/or braces. I’d like to do this, but as a one-liner from the command line:

while [ 1 ] do foo sleep 2 done 

15 Answers 15

while true; do foo; sleep 2; done 

By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.

$ while true > do > echo "hello" > sleep 2 > done hello hello hello ^C $ while true; do echo "hello"; sleep 2; done 

«if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.» was not true for me.

Excellent! Works perfectly on Mavericks (Mac OS-X 10.9) and allows me to keep a vpn running. Openconnect disconnects after a few hours with a bad cookie error. So I put the openconnect command in a shell script, sudo su to become root, and use this cmd line: while true; do sh /Users/myuser/bin/vpn ; done

It’s also possible to use sleep command in while’s condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done 

Well this does more than just changing the syntax — it will execute the command after the sleep. In the previous answer, the command is executed right away. Just something to note.

@DanGordon while echo thinking ; do sleep 2 ; done Of course if the [while] command fails, the loop exits, so you would have to while echo thinking || true ; do sleep 2 ; done but then you are back to while true ; .

while :; do foo; sleep 2; done 

@Pineapple Under the Sea: From the bash man page: (in section SHELL BUILTIN COMMANDS) : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.

You can use semicolons to separate statements:

$ while [ 1 ]; do foo; sleep 2; done 

You can also make use of until command:

until ((0)); do foo; sleep 2; done 

Note that in contrast to while , until would execute the commands inside the loop as long as the test condition has an exit status which is not zero.

while read i; do foo; sleep 2; done < /dev/urandom 
until [ ]; do foo; sleep 2; done 
while true; do echo 'while'; sleep 2s; done 
for ((;;)); do echo 'forloop'; sleep 2; done 

Using Recursion , (a little bit different than above, keyboard interrupt won't stop it)

Читайте также:  Посмотреть таблицы маршрутизации linux

Careful using units in sleep , like sleep 1h . In my zsh, it ignores the unit h and runs my command every 1 second. Do a quick man sleep to see what your environment's sleep command supports first. May save you a headache.

A very simple infinite loop.. 🙂

while true ; do continue ; done 

Fr your question it would be:

while true; do foo ; sleep 2 ; done 

For simple process watching use watch instead

I like to use the semicolons only for the WHILE statement, and the && operator to make the loop do more than one thing.

So I always do it like this

while true ; do echo Launching Spaceship into orbit && sleep 5s && /usr/bin/launch-mechanism && echo Launching in T-5 && sleep 1s && echo T-4 && sleep 1s && echo T-3 && sleep 1s && echo T-2 && sleep 1s && echo T-1 && sleep 1s && echo liftoff ; done 

Well, the use of && in the loop is the same as any other time really isn't it. Do you need the second thing to happen only if the first happens, then use && else ; suffices. Really, you want to keep the contents of that loop short and simple, ideally just one command, so a function or a script.

Careful using units in sleep , like sleep 1h . In my zsh, it ignores the unit h and runs my command every 1 second. Do a quick man sleep to see what your environment's sleep command supports first. May save you a headache.

If you want the while loop to stop after some condition, and your foo command returns non-zero when this condition is met then you can get the loop to break like this:

while foo; do echo 'sleeping. '; sleep 5; done; 

For example, if the foo command is deleting things in batches, and it returns 1 when there is nothing left to delete.

This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1 when the condition is met and exit with 0 when it should be run again.

For example, say you have a python script batch_update.py which updates 100 rows in a database and returns 0 if there are more to update and 1 if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:

while batch_update.py; do echo 'sleeping. '; sleep 5; done; 

Источник

Bash while loop to run command for specific time with examples

How to run a shell script for 5 minutes in a bash while loop? linux sleep. bash wait. bash for loop. bash script for loop. for loop in shell script. bash sleep. script timer. How to loop a function to run for certain minutes and then exit? How to run a command in a shell script for few minutes and exit? Script Timer condition while loop in a shell. while loop a function and sleep to run for 15 minutes. shell script to run a command every 5 minutes using bash while loop. bash while duration. shell for loop. run bash script timer.

Читайте также:  Linux find directories and remove

How to have a bash script run while loop until a specific time?

Earlier I had written an article on shell scripting interview questions along with their answers. In this article I will show some examples to run a function or command for specific time using bash while loop.

bash while loop for 5 minutes (define sleep duration as 30 seconds)

Here I have created a small script which will run for 5 minutes, and will run a command every 10 seconds. You can increase the Linux sleep timer from 10 seconds to any value for which you wish the script to wait before running the same command again. To wait for 1 minute you can use "sleep 1m"

Change the runtime variable value if you wish to change the total script timer for which the loop should run. So if you wish to run the while loop for 10 minutes then put runtime="10 minute"

#!/bin/bash runtime="5 minute" endtime=$(date -ud "$runtime" +%s) while [[ $(date -u +%s) -le $endtime ]] do echo "Time Now: `date +%H:%M:%S`" echo "Sleeping for 10 seconds" sleep 10 done

Running our script. I have trimmed the output.

# /tmp/testscript.sh Time Now: 23:56:26 Sleeping for 10 seconds Time Now: 23:56:36 Sleeping for 10 seconds Time Now: 23:56:46 Sleeping for 10 seconds Time Now: 23:56:56 Sleeping for 10 seconds Time Now: 23:57:06 Sleeping for 10 seconds > Time Now: 00:00:56 Sleeping for 10 seconds Time Now: 00:01:06 Sleeping for 10 seconds Time Now: 00:01:16 Sleeping for 10 seconds Time Now: 00:01:26 Sleeping for 10 seconds

bash while loop for 5 minutes (define sleep duration 1 minute)

Here we have kept our Linux sleep script timer as 1 minute so the date command will run every minute until 5 minute completes. You can replace the date command with any other command which you wish to execute.

#!/bin/bash runtime="5 minute" endtime=$(date -ud "$runtime" +%s) while [[ $(date -u +%s) -le $endtime ]] do echo "Time Now: `date +%H:%M:%S`" echo "Sleeping for 1 minute" sleep 1m done
# /home/oamsys/testscript.sh Time Now: 23:58:43 Sleeping for 1 minute Time Now: 23:59:43 Sleeping for 1 minute Time Now: 00:00:43 Sleeping for 1 minute Time Now: 00:01:43 Sleeping for 1 minute Time Now: 00:02:43 Sleeping for 1 minute Time Now: 00:03:43 Sleeping for 1 minute

bash while loop for 5 minutes (define sleep duration 10 seconds)

In this sample script I will use a different logic to run my command for 5 minutes for every 10 seconds. Now you can tweak the script and modify the Linux sleep script timer for the time period you wish to keep as interval before running the command.

#!/bin/bash wait_period=0 while true do echo "Time Now: `date +%H:%M:%S`" echo "Sleeping for 10 seconds" # Here 300 is 300 seconds i.e. 5 minutes * 60 = 300 sec wait_period=$(($wait_period+10)) if [ $wait_period -gt 300 ];then echo "The script successfully ran for 5 minutes, exiting now.." break else sleep 10 fi done

Running the sample script

# /tmp/testscript.sh Time Now: 00:27:26 Sleeping for 10 seconds Time Now: 00:27:36 Sleeping for 10 seconds Time Now: 00:27:46 Sleeping for 10 seconds Time Now: 00:27:56 Sleeping for 10 seconds Time Now: 00:28:06 Sleeping for 10 seconds Time Now: 00:28:16 Sleeping for 10 seconds > Sleeping for 10 seconds Time Now: 00:31:36 Sleeping for 10 seconds Time Now: 00:31:46 Sleeping for 10 seconds Time Now: 00:31:56 Sleeping for 10 seconds Time Now: 00:32:06 Sleeping for 10 seconds Time Now: 00:32:16 Sleeping for 10 seconds Time Now: 00:32:26 Sleeping for 10 seconds The script successfully ran for 5 minutes, exiting now..

How to wait for background process for certain time before terminating

Now you may also have a requirement to send a process to background and then wait for the process id to complete before exiting the script. But you may also not want to wait for infinite period and want a wrapper timeout which will monitor the wait command and then terminate the background process id if it is running for too long.

Here is a small script where we will send two commands 2 background and then wait for them to complete but if they took too long then those will be forcefully terminated.

#!/bin/bash echo "$(date +%H:%M:%S): start" pids=() timeout 10 bash -c 'sleep 20; echo "$(date +%H:%M:%S): job 1 terminated successfully"' & pids+=($!) timeout 2 bash -c 'sleep 5; echo "$(date +%H:%M:%S): job 2 terminated successfully"' & pids+=($!) for pid in $; do wait $pid exit_status=$? if [[ $exit_status -eq 124 ]]; then echo "$(date +%H:%M:%S): $pid terminated by timeout" else echo "$(date +%H:%M:%S): $pid exited successfully" fi done

Here, we are using timeout command to monitor the background process i.e. sleep. You can replace sleep with actual command or application. As you can see, the timeout value is lower then sleep to demonstrate that timeout will forcefully terminate the background process.

We will store the PIDs of the background process into a variable and use wait command to monitor those PIDs to complete.

~]# sh /tmp/script.sh 22:03:27: start 22:03:37: 7637 terminated by timeout 22:03:37: 7638 terminated by timeout

As expected, both the commands are forcefully terminated. timeout will terminate any process with exit code 124 so we monitor the exit code to confirm the behvaior.

Summary

In this tutorial I shared multiple commands and methods to run a loop for a specific time. You can use the same to control a for loop, until loop using a sleep timer. I also shared a sample script to wait for a back ground process for a certain period of time and then terminate it forcefully using the process id.

Further Reading

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

1 thought on “Bash while loop to run command for specific time with examples”

WOW.
How did you ever figure out the date command syntax to do this .. Ive read the help/man but maybe im missed something.

runtime="5 minute" endtime=$(date -ud "$runtime" +%s)

Источник

Оцените статью
Adblock
detector