Set -a with larger or smaller than breaking bash script

I wrote a bash script that runs curl only during working hours. For some reason, the hourly comparison fails when I add the -a operator (and for some reason my bash does not recognize "& &").

Despite the fact that the script is much larger, here is the corresponding snippet:

HOUR=`date +%k` if [ $HOUR > 7 -a $HOUR < 17 ]; then //do sync fi 

The script gives me an error:

 ./tracksync: (last line): Cannot open (line number): No such file 

However, this comparison is not subject to:

 if [ $DAY != "SUNDAY" -a $HOUR > 7 ]; then //do sync fi 

Is my syntax incorrect or is it a problem with my bash?

+4
source share
4 answers

You cannot use < and > in bash scripts as such. Use -lt and -gt to do this:

 if [ $HOUR -gt 7 -a $HOUR -lt 17 ] 

< and > are used by the shell to perform stdin or stdout redirects.

The comparison you say works by actually creating a file named 7 in the current directory.

As for && , it is also of particular importance to the shell and is used to create an AND list of commands.

Best documentation on all of these: man bash (and man test for information on comparison operators)

+13
source

There are several answers here, but none of them recommends the actual numerical context.

Here's how to do it in bash:

 if (( hour > 7 && hour < 17 )); then ... fi 

Note that expanding variables in a numeric context does not require "$".

+6
source

I suggest you use quotes around variable references and "standard" operators:

 if [ "$HOUR" -gt 7 -a "$HOUR" -lt 17 ]; ...; fi 
0
source

Try using [[ instead, because it is safer and has more features. Also use -gt and -lt for numerical comparisons.

 if [[ $HOUR -gt 7 && $HOUR -lt 17 ]] then # do something fi 
0
source

Source: https://habr.com/ru/post/1390072/


All Articles