问题
I wrote a bash script that performs a curl call only during business hours. For some reason, the hourly comparison fails when I add an "-a" operator (and for some reason my bash does not recognize "&&").
Though the script is much larger, here is the relevant piece:
HOUR=`date +%k`
if [ $HOUR > 7 -a $HOUR < 17 ];
then
//do sync
fi
The script gives me the error:
./tracksync: (last line): Cannot open (line number): No such file
However, this comparison does not fail:
if [ $DAY != "SUNDAY" -a $HOUR > 7 ];
then
//do sync
fi
Is my syntax wrong or is this a problem with my bash?
回答1:
You cannot use <
and >
in bash scripts as such. Use -lt
and -gt
for that:
if [ $HOUR -gt 7 -a $HOUR -lt 17 ]
<
and >
are used by the shell to perform redirection of stdin or stdout.
The comparison that you say is working is actually creating a file named 7
in the current directory.
As for &&
, that also has a special meaning for the shell and is used for creating an "AND list" of commands.
The best documentation for all these: man bash
(and man test
for details on comparison operators)
回答2:
There are a few answers here but none of them recommend actual numerical context.
Here is how to do it in bash:
if (( hour > 7 && hour < 17 )); then
...
fi
Note that "$" is not needed to expand variables in numerical context.
回答3:
I suggest you use quotes around variable references and "standard" operators:
if [ "$HOUR" -gt 7 -a "$HOUR" -lt 17 ]; ...; fi
回答4:
Try using [[
instead, because it is safer and has more features. Also use -gt
and -lt
for numeric comparison.
if [[ $HOUR -gt 7 && $HOUR -lt 17 ]]
then
# do something
fi
来源:https://stackoverflow.com/questions/8791231/multiple-a-with-greater-than-less-than-break-bash-script