if [ $string1 = $string2 -a $string3 = $string4 ]; then
results [: too many arguments. How to resolve this error?
if [ $string1 = $string2 -a $string3 = $string4 ]; then
results [: too many arguments. How to resolve this error?
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.
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.