开发者

Performing crontab-like numeric matching in a shell script

What would be the most straightforward way to emulate the same numeric matching that is used for the expressions in the first five fields of a crontab line?

For example, given inputs of a pattern "1,5-7,16,*/3" (silly example, I know) and a value "6", the output would be a boolean true.

If there isn't a dead simple solution, it'd be realistic in my situation to provide a third input which would specify the maximum value that an asterisk would need to match, so开发者_如何学运维 that asterisks (along with the hyphenated ranges) could be translated to a list of values and the input value could be matched against that list. (The list of the example pattern above would be "1,3,5,6,7,9,12,15,16,18", given a maximum value of "18".)

Thanks!


I'm mostly a ksh person, but my experience with bash says this should work (given your example), or at least point you towards what needs to be done.

hrVal=6
case ${hrVal} in   
   1|[5-7]|16 ) print -- "true" ;;
   * ) print -- "false" ;;
esac

Edit 2018-08-20 For bash, you'll need to change print -- to either echo .... or printf "%s\n".

In reality, I would remove the print -- "" stuff, and just call exit 0 or exit 1, which will then exit with the appropriate return code, that can then be tested by the calling process.


to include the rest of your example, I had to do

  hrVal=6
  eval "
    case ${hrVal} in

      1|[5-7]|16|$(( ${hrVal} / 3 )) ) print -- "true" ;;
      * ) print -- "false" ;;
    esac
 "

So, this could be exciting!

  • Parse each of 5 time bands as above
  • apply sed like commands to convert he entries like 1,5-7,16 into 1|[5-7]|16
  • trap and convert your math expressions into evaluatable expressions (oh, you can probably get the result before the case statement and just merge the value into the ....) save all derived values as variables,
  • use those variables as case targets, possible wrapping the whole thing and escaping chars as needed with an eval.
  • evaluate the combined truth of all 5 columns return values (any false == false)

(maybe it is (( ${hrVal} / 3 )) in bash )

IHTH

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜