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

半世苍凉 提交于 2020-01-06 02:27:10

问题


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
   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?


回答1:


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.




回答2:


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
 ...



回答3:


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 [ ].


来源:https://stackoverflow.com/questions/4763460/how-do-bashs-logical-operators-work-or-why-dont-they-work-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!