0

I'm learning bash script and I wrote something to better understand it. But below code really confuses me.

#!/bin/bash
ifEqual() {
   if [ "$3"="$1" ] ; then
   echo "$2=$1"
   else
   echo "heiheihei"
   fi
}
ifEqual "111" "666"

When I call this .sh file, it will print "666=111". But the function doesn't even have a third parameter. I expect this code to print "heiheihei". Can anyone explain to me what's happening here? Thank you in advance!

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Jaaaaaaay
  • 1,895
  • 2
  • 15
  • 24
  • This is effectively a duplicate of http://stackoverflow.com/questions/9581064/why-should-be-there-a-space-after-and-before-in-the-bash-script though technically this is asking about different missing spaces. – Etan Reisner Apr 14 '16 at 02:08

1 Answers1

3

You need spaces around the = for the test arguments to be parsed correctly.

if [ "$3" = "$1" ]; then

The way you wrote it, you're calling test with a single argument, and it just tests whether that argument is non-empty. Since the value of that argument is =111, it's not empty, so the result of the test is true.

Barmar
  • 741,623
  • 53
  • 500
  • 612