AlexMrKlim
AlexMrKlim

Reputation: 270

Shell - get android devices into array

I am new to shell scripting and am trying to get all the android devices in an array but my array is empty when the function is finished.

#!/bin/bash

declare -a arr
let i=0

MyMethod(){
  adb devices | while read line #get devices list
  do
    if [ ! "$line" == "" ] && [ `echo $line | awk '{print $2}'` == "device" ]
    then
      device=`echo $line | awk '{print $1}'`
      echo "Add $device"
      arr[$i]="$device"
      let i=$i+1
    fi
  done

echo "In MyMethod: ${arr[*]}"
}

################# The main loop of the function call #################

MyMethod
echo "Not in themethod: ${arr[*]}"

arr - is empty, what am I doing wrong?

Thanks for advice.

Upvotes: 0

Views: 1950

Answers (1)

Your probable problem is that piping a command causes it to run in a sub-shell, and variables that are changed there aren't propagated to the parent shell. You're solution would probably be something like:

adb devices > devices.txt
while read line; do
    [...]
done < devices.txt

where we save the output into an intermediary file to then be loaded into the while loop, or maybe use bash's syntax to store command output into intermediary temporary files:

while read line; do
    [...]
done < <(adb devices)

So the script becomes:

#!/bin/bash

declare -a arr
let i=0

MyMethod(){
  while read line #get devices list
  do
    if [ -n "$line" ] && [ "`echo $line | awk '{print $2}'`" == "device" ]
    then
      device="`echo $line | awk '{print $1}'`"
      echo "Add $device"
      arr[i]="$device" # $ is optional
      let i=$i+1
    fi
  done < <(adb devices)

echo "In MyMethod: ${arr[*]}"
}

################# The main loop of the function call #################

MyMethod
echo "Not in themethod: ${arr[*]}"

Some extra observations:

  1. To avoid errors, I would suggest you surround the back quotes in double quotes.
  2. The dollar is optional in arr[$i]=
  3. There is a specific test for empty strings: [ -z "$str" ] checks if string is empty (zero-length) and [ -n "$str"] checks if it isn't

Hope this helps =)

Upvotes: 1

Related Questions