0

I haven't done DOS in forever and can't recall the idiosyncracies with prefixing labels with %. I'm trying to write a script (others may also find it useful) to connect to ADB to a WiFi service running on my tablet.

@echo off
set def=192.168.1.21
if "%1" == "" (
    echo.Please supply the IP address of the ADB server/tablet.
    set /p ip=[%def%]
    if %ip% == "" (
      set ip=%def%
    )
) else (
    set ip=%1
    "C:\Program Files\adt-bundle-windows-x86_64-20130219\sdk\platform-tools\adb" connect "%ip":5555
)

The script should accept an IP address on the commandline, but if none is supplied, if should prompt the operator. If nothing is entered, the printed, square bracketed default should be used.

It seems to work, except that

set ip=%def%

never executes. I think I messed up the second IF statement. I just can't get the % signs in the right place!! Does anyone remember this old black magic?

Thanks.

4

1 回答 1

1

No need to set ip to the default if the user didn't enter anything. SET /P will preserve the existing value if the user presses Enter without typing anything. So all you need to do is set the value to the default before issuing SET /P.

Problems can occur if the user provides quotes for the arguments, and then your code adds additional quotes. It is generally safer to use "%~1" - the tilde strips any existing quotes, and then you add your own. This works if the argument is already quoted or not.

You probably should remove any existing quotes when you SET ip in your ELSE statement.

You are missing a % when you attempt to expand ip as an argument to adb. I suspect that you always want to execute the command. Your current code only executes the command if ip is provided as an argument.

I would structure the code as follows:

@echo off
setlocal
set "def=192.168.1.21"
set "ip=%~1"
if not defined ip (
  set "ip=%def%"
  echo Please supply the IP address of the ADB server/tablet.
  set /p "ip=[%def%] "
)
"C:\Program Files\adt-bundle-windows-x86_64-20130219\sdk\platform-tools\adb" connect "%ip%:5555"
于 2013-05-19T23:48:44.817 回答