Ananth Ananth - 4 years ago 137
Bash Question

Running a shell script for a certain duration

I want to be able to run a script on Linux shell (bash) for a certain duration and sleep for a different duration. I've written something like the following snippet. However, I see only the sleep happening correctly but the execution stops after first execution.

#!/bin/bash
some_work(){
echo "Working for $1 minutes"
if [ $1 -gt 0 ]
then
echo "Setting timer for $1 minutes"
run_end_time=$(($1 * 60))
start_time=SECONDS
curr_time=SECONDS
while $((curr_time < $((start_time + run_end_time)) )) :
do
#Do some work here
curr_time=SECONDS
done
fi
}

sleep_time(){
echo "Sleeping for $1 minutes"
sleep $(($1 * 60))
}

if [ $# -gt 1 ]
then
echo "Starting Steeplechase run for $1/$2"
while :
do
some_work $1
sleep_time $2
done
fi


The response I get is ./script.sh: line 30: 1: not found. Maybe I'm missing something bigtime here.

Answer Source

A few issues:

  • The conditional construct is while (( ... )); do and not while $(( ... )); do
  • The colon at the end of your line

    while $((curr_time < $((start_time + run_end_time)) )) :
    

    must not be there.

  • You're assigning the string SECONDS when you want the value of the variable; the assignments should look like var=$SECONDS instead of var=SECONDS.

Complete script, with a few suggestions and my idea of indentation:

#!/bin/bash

some_work () {
    echo "Working for $1 minutes"
    if (( $1 > 0 )); then
        echo "Setting timer for $1 minutes"
        run_end_time=$(($1 * 60))
        start_time=$SECONDS
        curr_time=$start_time  # Want this to be the same value
        while ((curr_time < $((start_time + run_end_time)) )); do
            #Do some work here
            curr_time=$SECONDS
        done
    fi
}

sleep_time () {
    echo "Sleeping for $1 minutes"
    sleep $(($1 * 60))
}

if (( $# > 1 )); then
    echo "Starting Steeplechase run for $1/$2"
    while true; do
        some_work $1
        sleep_time $2
    done
fi
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download