3

I'm trying to run a Postgres query like below and store the results into an array:

v2_ids=$(psql $(credstash get database/path/here) -tc "select distinct(user_id) from table where yada yada yada..." )

read -a arr_ids_temp <<< $v2_ids

Is there a better way to do this? It seems that read -a only grabs the first result sometimes and I'm not sure why.

2
  • user_id is not null or nullable in your table?.. Commented Jun 19, 2017 at 7:58
  • Yeah user_id is always populated Commented Jun 19, 2017 at 18:53

2 Answers 2

5

Refer the following code:

IFS=$'\n' res=(`psql -tA database username -c 'select column_name from table_name where blah blah...'`)
  • We must tell the bash to store the result in array based on '\n' delimiter.
  • psql options -tA for removing header/footer etc and removing leading and trailing blanks.

${res[0]} contains value of first row and each element in array contains the value of each row respectively.

Additional tips:

For taking all data in a row into array,

IFS='|' res=(`psql -tA database username -c 'select name1,name2,name3 from table_name where blah blah...'`)
  • Here I told bash to store the psql result in array based on | delimiter.
Sign up to request clarification or add additional context in comments.

Comments

1

That should work fine, but use psql with the options -A (unaligned output mode), -q (suppress informational output) and -t (no column names, headers and footers).

6 Comments

without distinct delimiter bash will split values by spaces - I think this happens to the OP
True; spaces in te result will make things much harder.
But user_id doesn't sound like it contains spaces.
:) true! I have a habit to complicate things
So psql -Aqt -d is giving this output in the v2_ids variable (good so far): ac566b6cf34d495c9de4be1d81c42c56 ba8fb335223b4919a8287c963ecd9d85 But then read -a arr_ids_temp <<< $v2_ids ...is only adding the first one to the array. Getting close though.
|

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.