Skip to content

Instantly share code, notes, and snippets.

@supercoffee
Created January 22, 2019 23:41
Show Gist options
  • Save supercoffee/72ab129704d4ce6bb04dedf19b6e6585 to your computer and use it in GitHub Desktop.
Save supercoffee/72ab129704d4ce6bb04dedf19b6e6585 to your computer and use it in GitHub Desktop.
ADB select
#!/usr/bin/env python
import sys
import os
import subprocess
import os.path
def get_file_path():
return os.path.expanduser("~/.adb-select")
def filter_empty_line(line):
return len(line) > 0
def map_device_id(line):
"""
:param line: adb device line
:type line: str
:return:
"""
return line.split()[0]
def format_selection_line(index, adb_raw_line):
return '%d) %s' % (index, adb_raw_line)
def write_selection(device_id):
output_path = get_file_path()
with open(output_path, "w") as output:
output.write(device_id)
def adb_select():
output = subprocess.check_output(["adb", "devices", "-l"])
lines = filter(filter_empty_line, output.splitlines()[1::])
device_ids = map(map_device_id, lines)
prompt_items = [format_selection_line(i, line) for i, line in enumerate(lines)]
for item in prompt_items:
print(item)
max_item_index = len(prompt_items) -1
selection = -1
while selection < 0 or selection > max_item_index:
selection = input("Enter selection [0 - %d] >> " % max_item_index)
write_selection(device_ids[selection])
def run_adb():
selection = ""
with open(get_file_path(), 'r') as input_file:
selection = input_file.readline()
if selection == "":
print("No device selected; exiting")
return
args = ["adb", "-s", selection] + sys.argv[1::]
subprocess.call(args)
def main():
if len(sys.argv) > 1:
run_adb()
else:
adb_select()
if __name__ == '__main__':
main()
@supercoffee
Copy link
Author

supercoffee commented Jan 22, 2019

ADB select

Quickly run commands on a device without having to type adb -s SOMEDEVICEID blah blah blah. Useful if you use ADB from the terminal with multiple devices connected.

Installation

  1. Paste this file somewhere in your executable path (I have a ~/scripts directory as part of my $PATH)
  2. Make it executable chmod +x adb-select.py
  3. Alias the command for quicker invocation. Add alias adbs='adb-select.py to your .bash_profile.
  4. Reload your bash profile source ~/.bash_profile

Selecting a device

Invoke adbs or adb-select.py to select from connected devices

ben$ adbs
0) emulator-5554          device product:sdk_gphone_x86 model:Android_SDK_built_for_x86 device:generic_x86
1) 8XV7N16116005231       device usb:342032384X product:angler model:Nexus_6P device:angler
Enter selection [0 - 1] >> 1

Running ADB commands to the selected device

Run any ADB command, but use adbs instead of adb at the beginning

ben$ adbs uninstall com.bendaschel.myapp
Success

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