Bash if statement with multiple conditions throws an error

前端 未结 4 2100
慢半拍i
慢半拍i 2020-11-30 18:20

I\'m trying to write a script that will check two error flags, and in case one flag (or both) are changed it\'ll echo-- error happened. My script:

my_error_f         


        
相关标签:
4条回答
  • 2020-11-30 18:42

    You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

    Using [[ operator

    a=$1
    b=$2
    if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
    then
         echo "Error"
    else
         echo "No Error"
    fi
    

    Using (( operator

    a=$1
    b=$2
    if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
    then
         echo "Error"
    else
         echo "No Error"
    fi
    

    Do not use -a or -o operators Since it is not Portable.

    0 讨论(0)
  • 2020-11-30 18:42

    Please try following

    if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
    then
        echo "WORKING"
    else
        echo "Out of range!"
    
    0 讨论(0)
  • 2020-11-30 18:43

    You can get some inspiration by reading an entrypoint.sh script written by the contributors from MySQL that checks whether the specified variables were set.

    As the script shows, you can pipe them with -a, e.g.:

    if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
        ...
    fi
    
    0 讨论(0)
  • 2020-11-30 18:51

    Use -a (for and) and -o (for or) operations.

    tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

    Update

    Actually you could still use && and || with the -eq operation. So your script would be like this:

    my_error_flag=1
    my_error_flag_o=1
    if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
          echo "$my_error_flag"
    else
        echo "no flag"
    fi
    

    Although in your case you can discard the last two expressions and just stick with one or operation like this:

    my_error_flag=1
    my_error_flag_o=1
    if [ $my_error_flag -eq 1 ] ||  [ $my_error_flag_o -eq 2 ]; then
          echo "$my_error_flag"
    else
        echo "no flag"
    fi
    
    0 讨论(0)
提交回复
热议问题