Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 823
Strawberry Avatar asked Nov 06 '10 01:11

Strawberry


People also ask

How do I compare two integer variables in bash?

So the very first operator to compare two integer type numbers or variables is the “equal to” operator in bash. After login, you need to open the terminal to start making bash files and creating code by “Ctrl+Alt+T”.

How do I compare two numbers in a bash script?

echo "enter two numbers"; read a b; echo "a=$a"; echo "b=$b"; if [ $a \> $b ]; then echo "a is greater than b"; else echo "b is greater than a"; fi; The problem is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.


2 Answers

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))  ... 
like image 73
Coding District Avatar answered Oct 01 '22 15:10

Coding District


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.

like image 23
jbremnant Avatar answered Oct 01 '22 14:10

jbremnant