How to do a logical OR operation for integer comparison in shell scripting?

1,016,426

Solution 1

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

Solution 2

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.

Solution 3

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.

Solution 4

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

if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi

Solution 5

If a bash script

If [[ $input -gt number  ||  $input  -lt number  ]]
then 
    echo .........
else
    echo .........

fi

exit
Share:
1,016,426
Strawberry
Author by

Strawberry

I want to learn industry practices and apply them to my projects to make myself successful

Updated on July 16, 2022

Comments

  • Strawberry
    Strawberry almost 2 years

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

    I have tried the following syntax with no success:

    if [ "$#" == 0 -o "$#" > 1 ] ; then
     echo "hello"
    fi
    
    if [ "$#" == 0 ] || [ "$#" > 1 ] ; then
     echo "hello"
    fi