Bash script - too many arguments

2019-08-06 13:13发布

问题:

Why doesn't the following work? All I'm trying to do is execute a adb command and, if the response contains a certain string, then doing something about it.

I keep getting an error [; too many arguments

VARIABLE=$(adb devices);
if [ "$VARIABLE" == *list of attached* ]; then
  echo "adb command worked";
fi

Any ideas?

回答1:

Try quoting the arguments inside [[ and ]]:

VARIABLE="$(adb devices)"
if [[ "$VARIABLE" == *"list of attached"* ]]; then
  echo "adb command worked";
fi

== needs single argument on either side. When you use [ "$VARIABLE" == *list of attached* ] then *list is the first argument after == and rest are considered extra arguments.



回答2:

You could alternatively try using BASH's binary operator =~ to do regex matching:

VARIABLE="$(adb devices)"
if [[ $VARIABLE =~ list\ of\ attached ]]; then
    echo "adb command worked"
fi


标签: bash shell