Skip to content

Instantly share code, notes, and snippets.

@zmdominguez
Last active September 21, 2023 14:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?

This gist expands on the initial functionality of the deeplinks.sh gist. This is a more flexible version that exposes the functionality to select a device and then use that serial number in one or more adb commands.

Companion blog post for usage is 🔗 here.

#!/bin/zsh
source "$(dirname "$0")/get_devices.sh"
# Grabs a serial number from all _available_ devices
# If there is only one device, grabs that serial number automatically
# If there are multiple devices, shows a chooser with the list of serial numbers
function getSerialNumber() {
serial_number=$(get_devices)
}
# Sends an interactive ADB command
# Usage: Use the usual ADB command, replacing `adb` with `adbi`
function adbi() {
getSerialNumber && adb -s "$serial_number" "$@"
}
# Display modes
alias darkMode='adbi shell cmd uimode night yes > /dev/null'
alias lightMode='adbi shell cmd uimode night no > /dev/null'
# Deep links
function deeplink() {
adbi shell am start -W -a android.intent.action.VIEW -d \""$1"\"
}
# Screen orientation
function rotatePortrait() {
getSerialNumber
adb -s "$serial_number" shell settings put system accelerometer_rotation 0
adb -s "$serial_number" shell settings put system user_rotation 0
}
function rotateLandscape() {
getSerialNumber
adb -s "$serial_number" shell settings put system accelerometer_rotation 0
adb -s "$serial_number" shell settings put system user_rotation 3
}
#!/bin/zsh
function get_devices() {
all_devices=$(command adb devices)
# Drop the title
all_devices=${all_devices#"List of devices attached"}
# Drop any unauthorised devices (i.e. USB debugging disabled or authorisations revoked)
valid_devices=$(echo $all_devices | grep -v "([[:alnum:]-]+[[:space:]]+unauthorized$)" | grep -oE "([[:alnum:]-]+[[:space:]]+device$)")
# Find how many valid devices we have
num_matches=$(echo $valid_devices | wc -l)
# If there are multiple, ask for which device to grab
if [[ $num_matches -gt 1 ]]; then
get_from_multiple
# Otherwise just grab the serial number
else
serial_number=$(echo $valid_devices | awk '{printf $1}')
fi
echo "$serial_number"
}
function get_from_multiple() {
# Display device serial numbers
find_matches=$(echo $valid_devices | egrep -io "([[:alnum:]-]+[[:space:]]+device$)" | awk '{print NR " - " $1}')
printf >&2 "Multiple devices found:\n%s\n" "$find_matches"
# Present chooser
echo >&2 -n "Select device: "
read -r selected_device
# Get the chosen serial number
serial_number=$(echo $find_matches | grep -E "${selected_device} - (.*)" | awk '{print $3}')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment