Shell script to check if Android device is connected over USB

Android devices has a daemon adbd which helps it to get connected over USB using adb command on linux host. If you are doing some kind of automation such as taking logs or installing some applications from ubuntu command line, the very first thing we need to make sure if our device is connected and if not connected report it to user and exit from the script. Following bash script helps for the same identification.

 $ vim check_if_android_device_connected.sh 
#!/bin/bash
ADB_PATH=$(which adb)

$ADB_PATH kill-server
$ADB_PATH start-server

check_if_android_device_connected() {
        ADB_OUT=`$ADB_PATH devices | awk 'NR>1 {print $1}'`
        if test -n "$ADB_OUT"
        then
                echo "device connected is $ADB_OUT"
        else
                echo "device is not connected, please check and restart the script"
                exit $?
        fi
}

check_if_android_device_connected

Now, lets run the script without connected the Android device over usb,

 $ bash check_if_android_device_connected.sh
device adb not connected, please check and restart the script

Now, lets connect Android device to PC/Laptop using USB and run the script again, [ Note: for this make sure you have adb debugging enabled from settings ]

$ bash check_if_android_device_connected.sh 
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
device connected is B2NGAA8831702707

Leave a Comment