0

I am getting the error "line 22 : [: too many arguments" on ubuntu server, and I not too sure how to fix it. Just wondering is there any solution for it? Here's my code.

if [ $? -eq 0 ]; then
   if [ $name = $ufname ]; then
      echo "Names are still the same"
   fi
fi
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
  • 1
    $name or $ufname may contain space – tristan Sep 12 '14 at 03:24
  • **Quote your string variables** and also add a prefix to prevent against empty string: `[ "z${name}" = "z${ufname}" ]`. That usually takes care of both `empty-string/unitialized` and `space in name` problems. – David C. Rankin Sep 12 '14 at 06:26
  • I thought quoting also takes care of empty string. bash will pass a placeholder empty-string argument to `[`. right? – anishsane Sep 12 '14 at 08:23

1 Answers1

2

One must be very careful with variables that may contain spaces or other special characters. Whitespace can really wrench up the works.

The best solution in bash is to use [[ instead of [. It handles whitespace with grace and style. I recommend just switching to [[ in all cases and never using [. [[ is better in all respects.

if [[ $? -eq 0 ]]; then
   if [[ $name = "$ufname" ]]; then
      echo "Names are still the same"
   fi
fi

The only reason to use [ is if portability is a concern--like if you're writing for plain sh rather than bash. In that case, you'll have to stick with [, and so you should quote your variables.

if [ $? -eq 0 ]; then
   if [ "$name" = "$ufname" ]; then
      echo "Names are still the same"
   fi
fi
Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578