String Return to Array

Asked

Viewed 118 times

0

I’m making a shellscript and have the return command:

$ sqlite3 banco.db 'select code from channels'

00 01 02 03

When I assign the return to a variable, everything becomes a single string.

$ export LISTA=$(sqlite3 banco.db 'select code from channels')
$ echo $LISTA

00 01 02 03

I would like each number to be the element of an array, as I can transform so that I can access as something like:

$ echo $LISTA[0]

00

$ echo $LISTA[1]

01

  • tries this way values=($(sqlite3 bank.db "select code from Channels")) cnt=${#values[@]} echo "number of variables in the array: $cnt"

1 answer

0

After placing the contents of the command inside the variable, vc must declare an array:

LISTA=$(sqlite3 banco.db 'select code from Channels')

echo $LIST

00 01 02 03

Now vc must declare an array with the contents of the variable, with a delimiter:

IFS=' ' ' read -r -a array <<< $LIST

echo ${array[0]}

00

echo ${array[1]}

01

echo ${array[2]}

02

echo ${array[3]}

03

Those echo are just examples, you don’t need to run them unless you want to see the content of each position in the array. Ready, declared and started array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.