0

I have a function where in I'm trying to compare the first parameter to a string, and then a separate boolean variable.

My sample bools:

EMS=true; 
COLL=true;

At a given point, both or any one or none of them can be true.

My function body:

function some_function() {
...
...
     if [ [ "$1" = "ez" ] &&  $EMS ] || [ "$1" = "coll" ] &&  $COLL ]; then
     #do mysterious magic
     ...
     ...
fi
}

I'm calling the function like so:

some_function ez
some_function coll

However when I execute the script, I run into this:

./deployBuild.sh: line 145: [: too many arguments

My if loop is incorrect and I'm unable to fix it. How do I proceed with?

Pseudo code of what I want to achieve:

if ("$1" is "ez" AND $EMS evaluates to true) OR ("$1" is "coll" AND $COL evaluates to true)
blueren
  • 2,730
  • 4
  • 30
  • 47

2 Answers2

2

@xaiwi gave you the right answer: use [[ instead of [ -- check Conditional Constructs in the bash manual.

Your logic is wrong though:

if [[ ( "$1" = "ez" &&  $EMS ) || ( "$1" = "coll"  &&  $COLL) ]]; 

With the value $EMS inside the [[...]], you get a "true" result if the value is non-empty -- see -n in Conditional Expressions in the manual

Since "true" is a bash command, you probably want one of

if ([[ $1 = "ez" ]] &&  $EMS) || ([[ $1 = "coll" ]] && $COLL); then ...
if { [[ $1 = "ez" ]] &&  $EMS; } || { [[ $1 = "coll" ]] && $COLL; }; then ... 

The first one uses subshells for command grouping; the second uses the current-shell grouping syntax -- reference.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

In recent Bash, you can try :

if  [[  ( "$1" = "ez"   &&  $EMS ) || (  "$1" = "coll"  &&  $COLL ) ]]

More portable solution is:

if  [  \( "$1" = "ez"   -a  $EMS \) -o \(  "$1" = "coll"  -a  $COLL \) ]
xiawi
  • 1,772
  • 4
  • 19
  • 21