1

我写了这个脚本:

#!/bin/sh

DEVICE=`sysctl hw.machine`

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

运行它后,我收到一条消息:./test: line 5: [: too many arguments为什么它不起作用?

4

1 回答 1

1

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

于 2012-07-09T20:01:53.057 回答