0

I am using psql to get a list of databases already running on my machine and a user-defined variable which has a list of database names. How can I check if the user-defined variables contain names that are already existing as a database? Here Is what I have done so far but the results are not consistent

x=`psql -l | awk '{print $1}' | grep -v "+" | grep -v "Name" | grep -v "List" | grep -v "(" | grep -v "template" | grep -v "postgres" | grep -v "|" | grep -v ":"`
db_name=test1,test2
array=(${x})
for i in "${array[@]}"
do
    for db in $(echo ${db_name} | tr ',' ' '); do
    if [[ ${i} != ${db} ]] ; then
        echo ${db} "Does not exists"  
    fi
done
kartoza-geek
  • 341
  • 1
  • 6
  • 20

2 Answers2

0

Try this:

DB_LIST=$(psql -l | awk '{print $1}' | grep -v "+" | grep -v "Name" | grep -v "List" | grep -v "(" | grep -v "template" | grep -v "postgres" | grep -v "|" | grep -v ":")

for DB_NAME in test1 test2
do
    DB_COUNT=$(echo $DB_LIST|grep $DB_NAME|wc -l)
    if [ $DB_COUNT -eq 1 ]; then 
        echo $DB_NAME exists
    fi
done
AAber
  • 1,562
  • 10
  • 14
  • You want simply `if echo "$DB_LIST" | grep -Fq "$DB_NAME"; then echo "$DB_NAME exists; fi`inside the loop. Also don't use uppercase for private variables. – tripleee Feb 13 '19 at 06:10
  • I like your suggestion. You have a typo in your one liner: "$DB_NAME Should be: "$DB_NAME" – AAber Feb 14 '19 at 06:26
0

Just create two arrays and then obtain their intersection as in Array intersection in bash

sqlist=($(psql -l | awk '$1 !~ /[+(|:]|Name|List|template|postgres/ {print $1}'))
userlist=(test1 test2)

intersection=()
for sqitem in "${sqlist[@]}"; do
    for usitem in "${userlist[@]}"; do
        if [[ $sqitem = $usitem ]]; then
            intersection+=("$sqitem")
        fi
    done
done
printf '%s\n' "${intersection[@]}"

Notice also the simplification of the useless uses of grep you had in your original psql postprocessing.

tripleee
  • 175,061
  • 34
  • 275
  • 318