0

I have a bash script that contains the following code.

#!/bin/bash

function wait_schedule () {
    if [[ ! -z ${1} ]];
    then
        if [[ ${1} -lt 2400 ]];
        then
            while [[ $(date +%H%M) -ne ${1} ]];
            do
                sleep 60
            done
        else
            echo "Error: The requested build time of ${1} is invalid."
            exit 1
        fi

    fi
}

wait_schedule ${1}
echo "Script completed"

When I run it, I get the following output.

[luigi@juventus: ~] ./test.sh
Script completed
[luigi@juventus: ~] date
Thu Feb 13 13:46:03 EST 2020
[luigi@juventus: ~] ./test.sh 1347
Script completed
[luigi@juventus: ~] ./test.sh 2500
Error: The requested build time of 2500 is invalid.
[luigi@juventus: ~] ./test.sh blah
(hangs forever)

How do I verify that the passed argument is actually a number?

  • 1
    Aside: `function funcname() {` merges the ancient pre-POSIX ksh syntax `function funcname {` and the POSIX-standardized syntax `funcname() {` in a way that's not compatible with *either* pre-POSIX ksh or the POSIX sh specification. Better to pick one or the other, rather than trying to use both; see also https://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Feb 13 '20 at 19:06
  • You could test to see if it's between 0 and 2400 like `[[ ${1} -lt 2400 && ${1} -gt 0 ]]` – JNevill Feb 13 '20 at 19:07
  • 1
    Moving on from that, though -- I wouldn't generally advise writing code that assumes that `sleep 60` will sleep *only* one minute. It's allowed to sleep longer than that (particularly if the system happens to be heavily loaded), and you don't want to miss your target time by accident and loop another day. Frankly, this is a job that prebuilt tools like systemd timers or your local cron or `at` implementations can handle well; if you really want to do it yourself, consider calculating the number of seconds' difference and passing that calculated value to a single invocation of `sleep`. – Charles Duffy Feb 13 '20 at 19:07
  • Yeah, this was a quick hack job to see if I could get it to work, and I'll modify it as you suggest. However, doing this made me wonder how I could actually test if a variable is numeric, and I haven't been able to find a simple way to do this. – k8AspvNUfYhkvpT9EX5YCSzoLouT0 Feb 13 '20 at 19:32

0 Answers0