0

I have a Bash script which should only execute in a specific time window (from midnight to 00:15 AM). But if I execute the function, I get [: too many arguments as an error message. How do I solve it? I still want to use Bash. I'm using Ubuntu Server 20.04 LTS.

Script:

currTime=`date +%H%M`
check_time_to_run() {
    tempTime=$1
    if [ $tempTime -gt 0 -a $tempTime -lt 015 ]; then
        echo "Time is after 0 AM and before 0:10 AM. Restarting Server."
    else
      echo "Time is not between 0 AM and 0:15 AM. Aborting restart."
      exit 1
    fi
}
Niklas
  • 103
  • 3
  • 1
    Paste your code into https://shellcheck.net, fix the errors or come back here with specific issues that you can't resolve. First thing is to put `#!/bin/bash` as the first line, which declares that it's a `bash` shell script. – roaima Dec 23 '21 at 16:19
  • 2
    Thanks, this site worked for me. The `#!/bin/bash` line is missing because i copy pasted this from my function. I used Double quote and `&&` instead of `-a`. Thank you – Niklas Dec 23 '21 at 16:28
  • And add in `if` double quotes around the variables. And do not use `015`, in some cases this can be accepted as octal number – Romeo Ninov Dec 23 '21 at 16:30
  • What should i use instead of `015`? – Niklas Dec 23 '21 at 16:38
  • 1
    Just `15`. If you have a leading zero on a value that is being treated as a number, the shell will assume you want it to be handled as octal. In this case here, `015` would be only 13 minutes, and you wouldn't be able to write `018` at all because it is not a valid octal number. – roaima Dec 23 '21 at 16:54
  • 1
    How are you calling your function? – Kusalananda Dec 23 '21 at 17:01
  • With `check_time_to_run $currTime` – Niklas Dec 23 '21 at 17:02
  • Pardon the silly question, but how can a value be greater than 15, AND less than 0? – Jim L. Dec 23 '21 at 19:38
  • My fault I updated it – Niklas Dec 23 '21 at 19:40

1 Answers1

0

You can try to break up your statements:

if [ $tempTime -gt 015 ] && [ $tempTime -lt 0 ]; then
  stuff...
fi

or use the double bracket to test for the a binary result of an expression:

 if [[ $tempTime -gt 015 && $tempTime -lt 0 ]]; then
  stuff...
 fi
Zach Tuttle
  • 141
  • 3
  • I took the lower option. Thanks. – Niklas Dec 23 '21 at 19:42
  • 1
    Note that there's also the issue of octal numbers. Bash takes numbers with leading zeroes as octal, and `date +%H%M` outputs the leading zero on hours before 10 am. So, e.g. 00:08 would print as `0008`, which is not a valid octal number. (Same would happen at any time before 8 am where the minutes are 8 or 9, e.g. 01:28; and every minute from 8 am to 10 am, e.g. 09:12.). You could use `10#` in front of the number to tell it to make it base ten, or just add a leading `1`. Also, the test should be 0 <= t < 15, not t > 15 && t < 0. – ilkkachu Dec 23 '21 at 19:56