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 
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"
                echo "device connected is $ADB_OUT"
                echo "device is not connected, please check and restart the script"
                exit $?


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

 $ bash
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 
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
device connected is B2NGAA8831702707
Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question