Wednesday, March 21, 2012

Selecting the adb device

I guess many, if like me, you normally use several devices an emulators. When this happens, you should obtain the serial number using

$ adb devices

then cut & paste the desired serial number into the command line and run the desired command again. Imagine how much time is wasted if this occurs tens or even hundreds of times during your day.

Hopefully, Linux and Mac OSX (or perhaps Cygwin if you are using Windows) give you the power to change what you don't like, so the following scripts will transparently allow you to select a device from the list when there's more than one a it wasn't specified in the command line.

android-select-deviceThis script, which is called android-select-device, is the responsibly of prompting the user for the selection of the device.

my-adbThis is the other component of our solution. This script, which we are calling my-adb will be the adb replacement which ultimately invokes the real adb.

#! /bin/bash# This command can be used as an alias for adb and it will prompt for the# device selection if needed# alias adb=my-adbset+xPROGNAME=$(basename $0)ADB=$(which adb)if [-z"$ADB"]thenecho"$PROGNAME: ERROR: cannot found adb"exit1fiset-eif [$#==0]then# no argumentsexec$ADBelif["$1"=='devices']then# adb devices should not accept -s, -e or -dexec$ADB devices
else# because of the set -e, if selecting the device fails it exitsS=$(android-select-device "$@")exec$ADB$S"$@"fi

final stepThe final step is to put this solution in place. To achieve this we need a way of replacing a normal adb command with the modified version. The alias shell's internal command is the best way of getting this done (you can add it to ~/.bash_aliases):

$ alias adb=my-adb

providing that the scripts are in your PATH and execute permission was granted.So now, every time you type adb without specifying the target device, android-select-device will prompt you for the selection: