I need to read the output of my command to array and store them in order to use after in my script.My script is;
let i=0
declare -a array
$PS -ef|$GREP -v grep|$GREP $NAME | $SED -n 's/.*-q\s\([0-9]\+\).*/\1/p' | while read line; do
array[$i]=$line
echo ${array[$i]}
(( i++ ))
echo ${#array[@]}
done < <($PS -ef|$GREP -v grep|$GREP $NAME | $SED -n 's/.*-q\s\([0-9]\+\).*/\1/p')
echo ${#array[@]}
So when the loop exits size of the array becomes 0 because of subshell. Is there a way to fix this?
You appear to have identical inputs on both ends of your pipe:
Try dropping the first so that the
whileloop doesn’t execute in a subshell:If you are using bash 4 or higher, you can replace the while loop with a call to
readarray: