ogs
ogs

Reputation: 1239

Bash parse dynamic arrays and store specific values in an other

I am sending a dbus-send command which returns something like :

method return sender=:1.833 -> dest=:1.840 reply_serial=2
   array of bytes [
      00 01 02 03 04 05 
   ]
   int 1
   boolean true

The "array of bytes" size is dynamic an can contains n values.

I store the result of the dbus-send command in an array by using :

array=($(dbus-send --session --print-repl ..readValue))

I want to be able to retrieve the values contained into the array of bytes and be able to display one or all of them if necessary like this :

data read => 00 01 02 03 04 05
or 
first data read => 00

First data is always reachable by {array[10]} and I think is it possible to use a structure like :

IFS=" " read -a array 
for element in "${array[@]:10}"
do
    ...
done

Any thoughts on how to accomplish this?

Upvotes: 0

Views: 220

Answers (1)

clt60
clt60

Reputation: 63974

You really should use some library for dbus, like Net::DBus or something similar.

Anyway, for the above example you could write:

#fake dbus-send command
dbus-send() {
    cat <<EOF
method return sender=:1.833 -> dest=:1.840 reply_serial=2
   array of bytes [
      00 01 02 03 04 05 
   ]
   int 1
   boolean true
EOF
}

array=($(dbus-send --session --print-repl ..readValue))

data=($(echo "${array[@]}" | grep -oP 'array\s*of\s*bytes\s*\[\s*\K[^]]*(?=\])'))

echo "ALL data ==${data[@]}=="
echo "First item: ${data[0]}"
echo "All items as lines"
printf "%s\n" "${data[@]}"

data=($(echo "${array[@]}" | sed 's/.*array of bytes \[\([^]]*\)\].*/\1/'))

echo "ALL data ==${data[@]}=="
echo "First item: ${data[0]}"
echo "All items as lines"
printf "%s\n" "${data[@]}"

for the both example prints

ALL data ==00 01 02 03 04 05==
First item: 00
All items as lines
00
01
02
03
04
05

Upvotes: 2

Related Questions