Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script spawning a process after a delay

Tags:

bash

shell

How can I spawn a process after a delay in a shell script? I want a command to start 60 seconds after the script starts, but I want to keep running the rest of the script without waiting 60 seconds first. Here's the idea:

#!/bin/sh # Echo A 60 seconds later, but without blocking the rest of the script sleep 60 && echo "A"  echo "B" echo "C" 

The output should be

B C ... 60 seconds later A 

I need to be able to do this all in one script. Ie. no creating a second script that is called from the first shell script.

like image 309
gerdemb Avatar asked Dec 16 '09 14:12

gerdemb


People also ask

How do you introduce a delay in shell script?

/bin/sleep is Linux or Unix command to delay for a specified amount of time. You can suspend the calling shell script for a specified time. For example, pause for 10 seconds or stop execution for 2 mintues. In other words, the sleep command pauses the execution on the next shell command for a given time.

Does a bash script wait for command to finish?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

How do I wait in bash script?

wait is typically used in shell scripts that spawn child processes that execute in parallel. To illustrate how the command works, create the following script: #!/bin/bash sleep 30 & process_id=$! echo "PID: $process_id" wait $process_id echo "Exit status: $?"

Are shell scripts slow?

Shell loops are slow and bash's are the slowest. Shells aren't meant to do heavy work in loops. Shells are meant to launch a few external, optimized processes on batches of data.


2 Answers

& starts a background job, so

sleep 60 && echo "A" & 
like image 100
nos Avatar answered Sep 22 '22 00:09

nos


Can't try it right now but

(sleep 60 && echo "A")&

should do the job

like image 37
lorenzog Avatar answered Sep 19 '22 00:09

lorenzog