سؤال

I've written this script:

#!/bin/sh

DEVICE=`sysctl hw.machine`

if [ $DEVICE = "hw.machine: iPhone3,1" ]
 then
  echo "Test Done"
 else
  echo "Test failed"
fi

After I run it I've got a message: ./test: line 5: [: too many arguments why isn't it working ?

هل كانت مفيدة؟

المحلول

You should always quote your expansions. [ is an alias for the test command. Just like any other command it takes arguments. The $DEVICE variable is expanded prior to the command running.

If $DEVICE contained whitespace, the command would look like this:

[ foo bar = "hw.machine: iPhone3,1" ]

In this example test is getting the arguments "foo" and "bar" before the comparison operator "=".

You need to quote the expansion:

if [ "$DEVICE" = "hw.machine: iPhone3,1" ]

Another note is that if using [[ in bash, this is not an issue as word splitting does not occur inside of [[.

See the following for more information on quoting: http://mywiki.wooledge.org/Quotes

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top