How to do a logical OR operation in shell scripting

前端 未结 8 2116
小蘑菇
小蘑菇 2020-11-27 08:55

I am trying to do a simple condition check, but it doesn\'t seem to work.

If $# is equal to 0 or is greater than 1 then say he

相关标签:
8条回答
  • 2020-11-27 09:42

    Sometimes you need to use double brackets, otherwise you get an error like too many arguments

    if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
      then
    fi
    
    0 讨论(0)
  • 2020-11-27 09:45

    If you are using the bash exit code status $? as variable, it's better to do this:

    if [ $? -eq 4 -o $? -eq 8 ] ; then  
       echo "..."
    fi
    

    Because if you do:

    if [ $? -eq 4 ] || [ $? -eq 8 ] ; then  
    

    The left part of the OR alters the $? variable, so the right part of the OR doesn't have the original $? value.

    0 讨论(0)
  • 2020-11-27 09:47

    If a bash script

    If [[ $input -gt number  ||  $input  -lt number  ]]
    then 
        echo .........
    else
        echo .........
    
    fi
    
    exit
    
    0 讨论(0)
  • 2020-11-27 09:50

    have you tried something like this:

    if [ $# -eq 0 ] || [ $# -gt 1 ] 
    then
     echo "$#"
    fi
    
    0 讨论(0)
  • 2020-11-27 09:53

    This code works for me:

    #!/bin/sh
    
    argc=$#
    echo $argc
    if [ $argc -eq 0 -o $argc -eq 1 ]; then
      echo "foo"
    else
      echo "bar"
    fi
    

    I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.

    man test
    

    for more details.

    0 讨论(0)
  • 2020-11-27 09:54

    This should work:

    #!/bin/bash
    
    if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
        echo "hello"
    fi
    

    I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

    if (("$#" > 1))
     ...
    
    0 讨论(0)
提交回复
热议问题