Why do I get an “unexpected operator” error for my condition in Bash?

前端 未结 2 2061
执笔经年
执笔经年 2020-12-04 03:02

I got the code for monitoring apache. The name of the file is test.sh. I changed the code a bit.

What I was looking for is, when I do:

.         


        
相关标签:
2条回答
  • 2020-12-04 03:33

    One of your variables ( user_arg, warn_req etc ) in the if condition might be empty.

    Better way to write that is with quoting the variables as (which may fail in your case if you want to compare as integers):

    if [ "${user_arg}" -ge "${warn_req}" -a "${user_arg}" -lt "${crit_req}" ]
    

    Or another way is to specify the default values so that if variable is null or undefined if won't fail as below.

    if [ ${user_arg:-0} -ge ${warn_req:-0} -a ${user_arg:-0} -lt ${crit_req:-0} ]
    
    0 讨论(0)
  • 2020-12-04 03:48

    If you don't need POSIX compatibility, you can use bash's arithmetic evaluation command instead:

    if (( user_arg >= 0 && user_arg < crit_req )); then
    

    Unset variables will be implicitly treated as 0-valued, so using default value expansion is unnecessary.

    0 讨论(0)
提交回复
热议问题