Check if database exists in PostgreSQL using shell

前端 未结 14 1389
南笙
南笙 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 07:20

    I'm combining the other answers to a succinct and POSIX compatible form:

    psql -lqtA | grep -q "^$DB_NAME|"
    

    A return of true (0) means it exists.

    If you suspect your database name might have a non-standard character such as $, you need a slightly longer approach:

    psql -lqtA | cut -d\| -f1 | grep -qxF "$DB_NAME"
    

    The -t and -A options make sure the output is raw and not "tabular" or whitespace-padded output. Columns are separated by the pipe character |, so either the cut or the grep has to recognize this. The first column contains the database name.

    EDIT: grep with -x to prevent partial name matches.

    0 讨论(0)
  • 2020-12-04 07:20
    • In one line:

    PGPASSWORD=mypassword psql -U postgres@hostname -h postgres.hostname.com -tAc 'select 1' -d dbnae || echo 0

    This will return 1 if db exists 0 if not

    • or more readable:
    if [ "$(PGPASSWORD=mypassword psql -U postgres@hostname -h postgres.hostname.com -tAc 'select 1' -d dbnae || echo 0 )" = '1' ]
    then
        echo "Database already exists"
    else
        echo "Database does not exist"
    fi
    
    0 讨论(0)
提交回复
热议问题