4

I am trying to load some sqlite3 output into an /n-delimited bash array. Seems like it should be a simple thing, but the read statement doesn't seem to produce any output. Echoing fqry just prior to the IFS statement confirms that the sqlite query is loading its output into a string correctly. But nothing appears to be getting into farray at all.

cmd="SELECT * FROM format"
fqry=`sqlite3 data.db "$cmd"`
IFS=$'\n' 
read -ra farray <<< "$fqry"
for f in "${farray[@]}"
do
echo "$f"
done

2 Answers 2

4

Use compound array assignment to create an indexed array instead of read:

cmd="SELECT * FROM format"
IFS=$'\n'
fqry=(`sqlite3 data.db "$cmd"`)

for f in "${fqry[@]}"; do
    echo "$f"
done
Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly. Thanks!
what if the entries contain newlines?
@Blauhirn then it gets complicated using bash. No matter what output line separator or IFS you use, you won't have any guarantee that it won't also appear in the db. Safest way would be to count the number of lines and then execute a query for each line (using LIMIT ...), but that has obvious drawbacks and is not atomic... I'd probably just use python instead.
@mata ok thanks. I solved it using select replace(the_column, char(10), 'my_linebreak_replacement12321') from ... and handle it accordingly. not optimal, but enough for my case.
2

You need to use the read -d option to define another delim, rather than the default newline character \n, to indicate the termination of the input line,

read -d '' -ra farray <<< "$fqry"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.