1
if [ $string1 = $string2 -a $string3 = $string4 ]; then 

results [: too many arguments. How to resolve this error?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

2 Answers2

1

With the single bracket test, [ .. ], you should use quotes around the variable names in the test brackets. Otherwise Bash will break the string on any spaces.

With:

$ s1="one two"
$ s2="one two"

If you do not quote your variable:

$ [ $s1 = $s2 ]; echo $?
-bash: [: too many arguments

But if you quote -- all is good:

$ [ "$s1" = "$s2" ]; echo $?
0

(0 means True in this case)

You can also use the Bash [[ ... ]] two bracket test and not use "quotes" SOMTIMES:

$ [[ $s1 == $s2 ]]; echo $?
0

For the 'and' part, you can use && either inside or outside the [[ ... ]] square braces:

$ s3="three"
$ s4="four"
$ [[ $s1 == $s2 ]] && [[ $s3 == $s4 ]]; echo $?
1
$ [[ $s1 == $s2 && $s3 == $s4 ]]; echo $?
1

But really -- it is best to quote all the time.

See this SO post.

dawg
  • 98,345
  • 23
  • 131
  • 206
  • 2
    As I pointed out in my comment to @AndreGelinas, you should double-quote at least the variables on the right of `==`, even though it's in `[[ ]]`. See [here](https://stackoverflow.com/questions/51002801/bash-a-a-not-true-square-bracket-affect-compare-result) for an example of why. But I really recommend double-quoting everything, to avoid having to keep track of where it's safe to leave variables unquoted. – Gordon Davisson Sep 25 '18 at 00:51
0

Or if strictly Bash/Ksh

#!/bin/bash

s1="one two"
s2="one two"
s3="three four"
s4="three four"


if [[ $s1 == $s2 && $s3 == $s4 ]]; then
        echo "All equals"
else
        echo "Some differences"
fi

Within [[ ]] there would be no word splitting normally and thus no need for quoting. Also, "&&" is generally preferred instead of "-a" for AND nowadays.

Hope it helps.

Andre Gelinas
  • 912
  • 1
  • 8
  • 10
  • 4
    I recommend using double-quotes around variables, even in `[[ ]]`, because in some cases it matters (see [here](https://stackoverflow.com/questions/51002801/bash-a-a-not-true-square-bracket-affect-compare-result) for an example). In this case, you could get away with double-quoting only the variables to the right of `==` (leaving the ones on the left unquoted), but keeping track of the rules and exceptions is really more trouble than it's worth -- just double-quote everything and you won't have to worry about it. – Gordon Davisson Sep 25 '18 at 00:49