1

I am preparing one script to compare 4 variables using single if statement.

Below is my script:

#!/bin/bash
a="abc"
b="abc"
c="deftdgr"
d="def"
if [[ $a = $b && $d =  ]]
then
    echo "inside if loop"
    break
else
    echo "inside else loop"
fi

My question is: is there any way i can use any wildcard to compare $d and $c so that tge if statement returns true value. And output comes as "inside if loop"?

closed as unclear what you're asking by ilkkachu, Jeff Schaller, Timothy Martin, Archemar, Christopher Apr 11 '18 at 14:05

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    It's not really clear what you want, but yes, you can use wildcards on the right-hand side of = to do pattern matching. [[ foo = f* ]], for example, would return true since the string foo matches the pattern f*. Likewise, [[ $c = $d* ]] would return true. – chepner Apr 10 '18 at 13:13
  • 1
    @chepner, in which case, you probably want $c = "$d"* so that the contents of $d are not taken as a pattern. – ilkkachu Apr 10 '18 at 13:17
  • 1
    @utkarsh, what are the complete criteria for success? Is it "(a equals b) and (c startswith d)"? Can you be completely specific? – glenn jackman Apr 10 '18 at 13:19
  • @glenn jackman - it should be like (a equals b ) and ( d should match everything starting with def [i.e. something like $d = $c*]) . Am i clear a bit? – acroniks Apr 10 '18 at 13:27
  • ... so you don't really need $c at all then? if [[ $a = "$b" && $d == def* ]] – glenn jackman Apr 10 '18 at 13:29
0

Just modify your if condition like below:-

#!/bin/bash
a="abc"
b="abc"
c="deftdgr"
d="def"
if [[ $a = "$b" && $c == "$d"* ]]
then
    echo "inside if loop"
    #break you don't need this at all
else
    echo "inside else loop"
fi
  • Working fine as expected... Thanks alot for quick response.. :) – acroniks Apr 11 '18 at 5:49
  • One more question. Can we use multiple and operators in single if statement? – acroniks Apr 11 '18 at 5:51
0

This is called the logical AND, logical operator.

exp1 -a  exp2 returns true if both exp1 and exp2 are true.

If you are comapring strings, you do:

  if [[ condition1 && condition2 ]]; then  echo "blah" ; fi 

One way to express this:

if [[ "$a" == "$b" && "$a" == "$c" ]]

When comaparing numbers, you do:

  if (( (a == b) && (a == c) )); then echo "blah" ; fi 

Doc click

Not the answer you're looking for? Browse other questions tagged or ask your own question.