2

I was hoping somebody would be able to help me with this I need a loop for a shell script that will run what is inside the loop for 15 seconds. SO for example

if (true)
    run command for 15 seconds
fi
    kill PID

I am new to shell scripting, so i am lost with this. Also I am using a debian instll if that makes any difference

Any help is appreciated

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
AlanF
  • 1,591
  • 3
  • 14
  • 20
  • See http://stackoverflow.com/questions/526782/how-do-i-limit-the-running-time-of-a-bash-script/526815#526815 – paxdiablo Apr 23 '12 at 08:45
  • 1
    possible duplicate of [Bash script that kills a child process after a given timeout](http://stackoverflow.com/questions/5161193/bash-script-that-kills-a-child-process-after-a-given-timeout) – Charles Duffy Apr 23 '12 at 15:53

2 Answers2

3

Are you looking for the timeout command?

Michael Wild
  • 24,977
  • 3
  • 43
  • 43
0

The following bash script might work for you. The script will set the initial epoch time as a variable prior to beginning a loop. While the loop runs an additional variable will be set with the current epoch time. Both epoch times will be compared and as long as the difference is less than or equal to 15 your command will continue to run. Note that in the script below the current command running is 'echo "counting ${COUNTER}"'. You should change this portion of the script to match what you are trying to accomplish. Once the difference of the two epoch times is greater than 15 the script will exit. You will need to initate your kill command at this point. If an error does occur you should see "ERROR... YourScript.sh failed" in "YourLogFile" (set your log file to what you would like)

NOTE: Whatever you are attempting to run while inside this loop may run many many many times within the 15 second period. By utilizing the script below as a test you will see that the echo command runs more than 50 times per second.

#!/bin/bash

LOOP="true"
INITIAL_TIME=$(date "+%s")

while [[ ${LOOP} == true ]]; do

    CURRENT_TIME=$(date "+%s")
    COUNTER=$(expr ${CURRENT_TIME} - ${INITIAL_TIME})

    if [[ ${COUNTER} -le "15" ]]; then

        echo "counting ${COUNTER}"
        # RUN YOUR COMMAND IN PLACE OF THE ABOVE echo COMMAND

    elif [[ ${COUNTER} -gt "15" ]]; then
        exit 0
            #INITIATE YOUR KILL COMMAND IN PLACE OF OR BEFORE THE exit
    else
        echo "ERROR... YourScript.sh failed" >> /YourLogFile
    fi

done
E1Suave
  • 268
  • 2
  • 10
  • The command, replacing `echo "counting ${COUNTER}"` will block, and not terminate - say a download of a long video over slow connection. – user unknown Apr 23 '12 at 16:55