0

By running this line of code:

psql -c "\l" -p 54049

I am getting the below result:

enter image description here

my questions are a bit general BASH

1- how can I parse a table like this in BASH

2- what are this type of tables called

3- any hands on training tutorials for learning BASH in the hard way

4- and how can I parse this table as arrays of an array so that each row will be as an array and each its elements to be as the columns?

Main question : I want to compare my manual input with this table therefore if my input db name exists in the result it will continue else it will else again.

Here is the code which is not working:

dbsList=`psql -c "\l" -p 54049 | awk '{ print $1 }'`

echo "Please enter a valid DB name you want to backup:"
read dbName

contains() {
    [[ $1 =~ (^|[[:space:]])"$2"($|[[:space:]]) ]] && echo 0 || echo 1
}

contains dbsList dbName

while [ `contains dbsList dbName` -eq 1 ]
do
echo "Please enter a valid DB name you want to backup:"
read dbName
done
3
  • better use psql -c "select string_agg(datname,',') from pg_database" -p 54049 for the list Commented Apr 4, 2017 at 13:48
  • And a short answer: Don't do this in bash. Use a real programming language for, if you want to write maintainable code Commented Apr 4, 2017 at 13:53
  • i would probably use python for it Commented Apr 4, 2017 at 13:58

1 Answer 1

3

don't parse output of \l metacommand, better use select pg_database eg:

-bash-4.2$ for i in $(psql -c "select datname from pg_database" -Xt); do echo "you can do logic against $i"; done;
you can do logic against template1
you can do logic against template0
you can do logic against postgres

and answer to you questions:

  1. bash was not designed for parsing, (you can do it, but the question is to wide)
  2. this is not a table - it is the return of select query
  3. please, start with any reading on this, eg http://tldp.org and psql
  4. too much pointless work, consider the example above
Sign up to request clarification or add additional context in comments.

2 Comments

i agree on all the points that's why i wanted some materials from experienced people so that i can learn to do things like this.
I updated the answer to include the link to some online docs for bash. It is very short and will give you the basic idea of what bash is and how you use it

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.