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
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply