Check if database exists in PostgreSQL using shell

前端 未结 14 1387
南笙
南笙 2020-12-04 06:13

I was wondering if anyone would be able to tell me about whether it is possible to use shell to check if a PostgreSQL database exists?

I am making a shell script and

相关标签:
14条回答
  • 2020-12-04 06:53

    The following shell code seems to work for me:

    if [ "$( psql -tAc "SELECT 1 FROM pg_database WHERE datname='DB_NAME'" )" = '1' ]
    then
        echo "Database already exists"
    else
        echo "Database does not exist"
    fi
    
    0 讨论(0)
  • 2020-12-04 06:53

    kibibu's accepted answer is flawed in that grep -w will match any name containing the specified pattern as a word component.

    i.e. If you look for "foo" then "foo-backup" is a match.

    Otheus's answer provides some good improvements, and the short version will work correctly for most cases, but the longer of the two variants offered exhibits a similar problem with matching substrings.

    To resolve this issue, we can use the POSIX -x argument to match only entire lines of the text.

    Building on Otheus's answer, the new version looks like this:

    psql -U "$USER" -lqtA | cut -d\| -f1 | grep -qFx "$DBNAME"
    

    That all said, I'm inclined to say that Nicolas Grilly's answer -- where you actually ask postgres about the specific database -- is the best approach of all.

    0 讨论(0)
  • 2020-12-04 06:55

    You can create a database, if it doesn't already exist, using this method:

    if [[ -z `psql -Atqc '\list mydatabase' postgres` ]]; then createdb mydatabase; fi
    
    0 讨论(0)
  • 2020-12-04 07:00

    psql -l|awk '{print $1}'|grep -w <database>

    shorter version

    0 讨论(0)
  • 2020-12-04 07:01

    For completeness, another version using regex rather than string cutting:

    psql -l | grep '^ exact_dbname\b'
    

    So for instance:

    if psql -l | grep '^ mydatabase\b' > /dev/null ; then
      echo "Database exists already."
      exit
    fi
    
    0 讨论(0)
  • 2020-12-04 07:03

    I'm still pretty inexperienced with shell programming, so if this is really wrong for some reason, vote me down, but don't be too alarmed.

    Building from kibibu's answer:

    # If resulting string is not zero-length (not empty) then...
    if [[ ! -z `psql -lqt | cut -d \| -f 1 | grep -w $DB_NAME` ]]; then
      echo "Database $DB_NAME exists."
    else
      echo "No existing databases are named $DB_NAME."
    fi
    
    0 讨论(0)
提交回复
热议问题