开发者

How do bash's logical operators work (or why don't they work here)?

I have the following wrapper script:

#!/bin/bash

$local_time=`date +%H%M`
if [ $local_time -ge 1430 ] && [ $local_time -le 2230 ] ||
   [ $local_time -ge 0300 ] && [ $local_time -le 0400 ]
then
   echo 'pass'
else
开发者_JS百科   echo 'skip'
fi

The idea being to create a wrapper script that runs a script between two disjoint time intervals. Each of the expressions being OR'd is evaluated correctly, however, when I OR both expressions, the test fails.

How do I fix this?


You have two problems

  1. You don't prefix your variables with a $ when you assign to them, only when you expand them
  2. You need to enforce operator precedence with parens ( )

Also, since you're already using bash, might as well use its better syntax with the (( )) construct that allows you to use the comparison operators < > == != and you can use $() for command substitution instead of the backticks/gravemarks

#!/bin/bash

local_time=$(( 10#$( date +'%H%M' ) ))
if (( ( local_time >=    1430 && local_time <=    2230 ) ||
      ( local_time >= 10#0300 && local_time <= 10#0400 )    ))
then
  echo 'pass'
else
  echo 'skip'
fi

Numbers that start with a zero are interpreted as octal.
Also, any number that start with 0 and contains an 8 or 9 will print an error.
Prefixing (10#) solves that.


bash does not have "logical operators"; those are "conditional chains". Logic belongs in the test.

if [[ ( 10#${local_time} -ge 10#1430 && 10#${local_time} -le 10#2230 ) || \
      ( 10#${local_time} -ge 10#0300 && 10#${local_time} -le 10#0400 ) ]]
then
 ...


You just need to enforce proper precedence with a couple of parenthesis:

#!/bin/bash

local_time=$(date +%H%M)
if ( [ "$local_time" -ge 1430 ] && [ "$local_time" -le 2230 ] ) ||
   ( [ "$local_time" -ge 0300 ] && [ "$local_time" -le 0400 ] )
then
   echo 'pass'
else
   echo 'skip'
fi

Reason: Inside an AND-OR list && and || have equal precedence.
Note: Inside [ ] numbers that start with 0 are not interpreted as octals.

Other changes:

  • The left side of an equal should have just the variable name (No $).
  • It is recommended to use $() instead of ``.
  • Quote variables inside [ ].
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜