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.
  • 38,596
  • 16
  • 96
  • 104
Jaaaaaaay
  • 1,735
  • 2
  • 14
  • 22
  • 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
  • 669,327
  • 51
  • 454
  • 560