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.
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:
where we save the output into an intermediary file to then be loaded into the
whileloop, or maybe use bash’s syntax to store command output into intermediary temporary files:So the script becomes:
Some extra observations:
arr[$i]=[ -z "$str" ]checks if string is empty (zero-length) and[ -n "$str"]checks if it isn’tHope this helps =)