Advertisement
Advertisement


How to do a logical OR operation in shell scripting


Question

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
2019/04/22
1
577
4/22/2019 7:20:18 AM

Accepted Answer

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))
 ...
2018/04/26
998
4/26/2018 10:40:20 AM

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.

2010/11/06

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.

2015/06/10

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

if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi
2016/05/02

If a bash script

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

fi

exit
2018/06/07

have you tried something like this:

if [ $# -eq 0 ] || [ $# -gt 1 ] 
then
 echo "$#"
fi
2010/11/06

Source: https://stackoverflow.com/questions/4111475
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]