Skip to content

Instantly share code, notes, and snippets.

@mlagerberg
Last active November 21, 2017 09:12
Show Gist options
  • Save mlagerberg/0696ab868e3506079b321003813dc2d1 to your computer and use it in GitHub Desktop.
Save mlagerberg/0696ab868e3506079b321003813dc2d1 to your computer and use it in GitHub Desktop.
[ADB control script that simplifies working with multiple devices] #android #adb
#!/bin/bash
# Get list of only the device identifiers
# 1 list devices
# 2 grep away the line 'list of devices'
# 3 grep away newline at the end
# 4 cut off everything but the first part (identifier)
ALL=`adb devices -l`
#LIST=`adb devices | grep -v devices | grep device | cut -f1`
LIST=`echo "$ALL" | grep -v devices | grep device | awk '{print $1}'`
# Similar, but grabbing the model and brand instead
# 4 cut off everything but the last part ('model:HTC_One_X')
# 5 take only the part after the colon ('HTC_One_X')
DEVICES=`echo "$ALL" | grep -v devices | grep device | awk '{print $5}' | cut -d':' -f2`
# 6 replace underscores with spaces
DEVICES=`echo "${DEVICES//_/ }"`
# Count lines
COUNT=`echo "$LIST" | wc -l`
if ((COUNT==0))
then
echo "No devices connected."
exit 1
elif ((COUNT==1))
then
# execute regular command
adb $@
else
# Show chooser
while true; do
echo "Choose a device to execute this command on:"
echo " adb $@"
echo ""
i=1
while read -r line; do
echo " [$i] $line"
i=$((i+1))
done <<< "$DEVICES"
echo " [a] All"
echo " [c] Cancel"
echo ""
read -n1 -s n
if (( n <= COUNT && n > 0 )); then
SERIAL=`echo "$LIST" | head -n $n | tail -n 1`
echo "adb -s $SERIAL $@"
adb -s $SERIAL $@
break
elif [[ $n == "c" ]]; then
echo "Canceled."
break
elif [[ $n == "a" ]]; then
for SERIAL in $LIST; do
echo "adb -s $SERIAL $@"
adb -s $SERIAL $@
done
break
else
echo "Let's try that again."
continue
fi
done
fi
@mlagerberg
Copy link
Author

mlagerberg commented Jun 2, 2017

Usage:

  1. Make an alias for this script, e.g. adb2, or simply run the script whenever you would otherwise run adb.
  2. Run a regular adb command on the script: ./adb.sh install -r my_app.apk
  3. If you have multiple devices attached, the script will list them all and asks which one to run it on
  4. Hit a number, the command will be executed on that device

Example:

./adb.sh install -r my_app.apk

Output:

Choose a device to execute this command on:
  adb install -r my_app.apk

  [1] Nexus 6P
  [2] Nexus 5
  [a] All
  [c] Cancel

>2
adb -s 168f8abc8af6 install -r my_app.apk
my_app.apk pushed. 5.9 MB/s (15416456 bytes in 2.505s)
	pkg: /data/local/tmp/my_app.apk
Success

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment