Skip to content

Instantly share code, notes, and snippets.

@unique-EJ
Created October 25, 2024 11:48
Show Gist options
  • Select an option

  • Save unique-EJ/15f0b47018a0fd37ef1799aa88d16671 to your computer and use it in GitHub Desktop.

Select an option

Save unique-EJ/15f0b47018a0fd37ef1799aa88d16671 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Send text to Android device using ADB, emulating keyboard input.
# Based on a script from https://android.stackexchange.com/a/105881/223695
# and extended to support special characters.
# CC BY-SA 3.0 - Share under same license, attribute the creator, indicate changes.
# From Matthijs Kooijman's answer, https://android.stackexchange.com/a/176590/359828
if [[ "$1" != "" ]]
then
TEXT="$1"
else
read -s -r -p "Enter text you want to insert: " TEXT
fi
escape() {
# Encapsulate the string in $'', which enables interpretation of
# "\xNN" escapes in the string. This is not POSIX-sh, but an extension
# documented by bash and also supported by the Android sh.
echo -n "$'"
# Process each character in $1 one by one
for (( i=0 ; i<${#1}; i++ )); do
# Extract the i'th character
C="${1:$i:1}"
if [ "$C" = ' ' ]; then
# Encode spaces as %s, which is needed for Android's
# "input text" command below 6.0 Marshmellow
# See https://stackoverflow.com/documentation/android/9408/adb-shell/3958/send-text-key-pressed-and-touch-events-to-android-device-via-adb
echo -n '%s'
else
# Encode everything else as "\xNN", to prevent them from being
# interpreted by the Android shell
printf '\\x%02x' "'$C"
fi
done
# Terminate the $''
echo -n "'"
}
ESCAPED_TEXT=`escape "$TEXT"`
adb shell input text "$ESCAPED_TEXT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment