LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   syntax for two different conditions in if statement (https://www.linuxquestions.org/questions/linux-newbie-8/syntax-for-two-different-conditions-in-if-statement-4175516511/)

vjlxmi 08-27-2014 07:06 AM

syntax for two different conditions in if statement
 
hello
i am trying to write a command like
if [ a == b ] && [ c == d ]
it gives me an error [: missing `]'
can any one help me with the syntax and also explain what this error means
thanks in advance

pan64 08-27-2014 07:12 AM

that line looks actually ok, so you should tell us explicitly what caused your problem.

vjlxmi 08-27-2014 07:23 AM

I have no idea what the problem is. Maybe [: missing `]'means that there is a bracket missing. I checkd and all the brackets are closing. Is there any other way of writing the syntax?

grail 08-27-2014 08:12 AM

Do you have spaces around the brackets? Remember that [ is a synonym for test and you would not write, iftesta==b]

schneidz 08-27-2014 08:25 AM

this worx for me:
Code:

[schneidz@hyper Documents]$ bash --version
GNU bash, version 4.2.10(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
[schneidz@hyper Documents]$ if [ a == b ] && [ c == d ]
> then
>  echo hello world
> else
>  echo l33t h4x0rz
> fi
l33t h4x0rz


jpollard 08-27-2014 10:12 AM

Well... assuming a b and c are shell variables, you need $a $b and $c to test the VALUE of the variables.

As in:

Code:

a=1
b=1
c=1

if [ a == b ] && [ b == c ]; then
    echo true
else
    echo false
fi

comes up false, but to test the value you need:

Code:

a=1
b=1
c=1

if [ $a == $b ] && [ $b == $c ]; then
    echo true
else
    echo false
fi

will come up true.

Note "==" is a string comparison, thus a == b is always false... If a/b/c are supposed to be numeric, then use -eq.


All times are GMT -5. The time now is 04:00 PM.