Reputation: 2506
I want to construct an arry with the result of a SQLite query. I do
result=`sqlite3 "$database" 'SELECT id,value FROM table'`
I obtain
1|value for id 1
2|value for id 2
(By defaut, sqlite use | as separator). What I want is using the id as the key in the bash array, and value as the bash value.
If I type directly
array=([1]="value for id 1" [2]="value for id 2")
It work great ! So I modify result this way :
result=`sqlite3 "$database" 'SELECT id,value FROM table' | sed 's/^/[' | sed 's/|/]="/' | sed 's/$/"/' | sed ':a;N;$!ba;s/\n/ /g'`
and when i do echo "$result", I succesfully obtain :
[1]="value for id 1" [2]="value for id 2"
But now, when I do
array=($result)
array=("$result")
array=($(echo -n $result))
array=($(echo -n "$result"))
array=(`echo -n $result`)
array=(`echo -n "$result"`)
None of them work. If I do
for i in "${!array[@]}";do
echo "key = $i"
echo "val = ${array[$i]}"
done
I end up with something like
key = 0
val = [1]="value
key = 1
val = for
key = 2
val = id
key = 3
val = 1"
key = 4
val = [2]="value
key = 5
val = for
key = 6
val = id
key = 7
val = 2"
What's wrong ? How can I initalize an array with $result ?
Upvotes: 0
Views: 44
Reputation: 295815
Process substitution results aren't eval
uated as code. This is, in short, a Very Good Thing -- if you had a value containing $(rm -rf $HOME)
, you wouldn't want it to be any other way.
Instead, explicitly read your results and assign them to your array:
declare -a array=( )
while IFS='|' read -r key value; do
array[$key]=$value
done < <(sqlite3 "$database" 'SELECT id,value FROM table')
Upvotes: 1