program tip

쉘을 사용하여 PostgreSQL에 데이터베이스가 있는지 확인하십시오.

radiobox 2020. 7. 26. 12:49
반응형

쉘을 사용하여 PostgreSQL에 데이터베이스가 있는지 확인하십시오.


셸을 사용하여 PostgreSQL 데이터베이스가 있는지 확인할 수 있는지 여부를 누군가가 말해 줄 수 있는지 궁금합니다.

쉘 스크립트를 만들고 있는데 데이터베이스가 존재하지 않지만 데이터베이스를 구현하는 방법을 볼 수 없었던 경우에만 데이터베이스를 작성하려고합니다.


Arturo 솔루션의 다음 수정을 사용합니다.

psql -lqt | cut -d \| -f 1 | grep -qw <db_name>


그것이하는 일

psql -l 다음과 같은 것을 출력합니다 :

                                        List of databases
     Name  |   Owner   | Encoding |  Collate   |   Ctype    |   Access privileges   
-----------+-----------+----------+------------+------------+-----------------------
 my_db     | my_user   | UTF8     | en_US.UTF8 | en_US.UTF8 | 
 postgres  | postgres  | LATIN1   | en_US      | en_US      | 
 template0 | postgres  | LATIN1   | en_US      | en_US      | =c/postgres          +
           |           |          |            |            | postgres=CTc/postgres
 template1 | postgres  | LATIN1   | en_US      | en_US      | =c/postgres          +
           |           |          |            |            | postgres=CTc/postgres
(4 rows)

순진한 접근 방식을 사용한다는 것은 "목록,"액세스 "또는"행 "이라는 데이터베이스를 검색하는 것이 성공한다는 것을 의미하므로이 명령을 내장 명령 줄 도구를 통해 첫 번째 열에서만 검색하도록 파이프합니다.


-t플래그는 머리글과 바닥 글을 제거합니다 :

 my_db     | my_user   | UTF8     | en_US.UTF8 | en_US.UTF8 | 
 postgres  | postgres  | LATIN1   | en_US      | en_US      | 
 template0 | postgres  | LATIN1   | en_US      | en_US      | =c/postgres          +
           |           |          |            |            | postgres=CTc/postgres
 template1 | postgres  | LATIN1   | en_US      | en_US      | =c/postgres          +
           |           |          |            |            | postgres=CTc/postgres

다음 비트 cut -d \| -f 1는 출력을 수직 파이프 |문자 (백 슬래시로 쉘에서 이스케이프)로 나누고 필드 1을 선택합니다.

 my_db             
 postgres          
 template0         

 template1         

grep -w전체 단어와 일치하므로이 temp시나리오에서 검색하는 경우 일치하지 않습니다 . -q옵션은 화면에 기록 된 모든 출력을 억제하므로 명령 프롬프트에서 대화식으로이를 실행하려는 경우 해당 항목을 제외하여 -q즉시 표시되도록 할 수 있습니다 .

참고 grep -w일치의 숫자, 숫자와 정확히 PostgreSQL을에 인용 부호로 둘러싸이지 않은 데이터베이스 이름에 사용할 수있는 문자의 집합입니다 밑줄 (하이픈이 인용되지 않은 식별자 법률되지 않습니다). 다른 캐릭터를 사용하면 효과가 grep -w없습니다.


이 전체 파이프 라인의 종료 상태 0는 데이터베이스가 존재하는 경우 (성공) 또는 존재 1하지 않는 경우 (실패)입니다. 쉘은 특수 변수 $?를 마지막 명령의 종료 상태로 설정합니다 . 조건부에서 직접 상태를 테스트 할 수도 있습니다.

if psql -lqt | cut -d \| -f 1 | grep -qw <db_name>; then
    # database exists
    # $? is 0
else
    # ruh-roh
    # $? is 1
fi

다음 쉘 코드가 나를 위해 작동하는 것 같습니다.

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

postgres@desktop:~$ psql -l | grep <exact_dbname> | wc -l

지정된 데이터베이스가 존재하면 1을, 그렇지 않으면 0을 리턴합니다.

또한 이미 존재하는 데이터베이스를 만들려고하면 postgresql은 다음과 같은 오류 메시지를 반환합니다.

postgres@desktop:~$ createdb template1
createdb: database creation failed: ERROR:  database "template1" already exists

postgresql을 처음 사용하지만 다음 명령은 데이터베이스가 있는지 확인하는 데 사용한 명령입니다.

if psql ${DB_NAME} -c '\q' 2>&1; then
   echo "database ${DB_NAME} exists"
fi

간결하고 POSIX 호환 양식에 대한 다른 답변을 결합하고 있습니다.

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

true( 0) 의 반환은 존재한다는 의미입니다.

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.


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

#!/bin/sh
DB_NAME=hahahahahahaha
psql -U postgres ${DB_NAME} --command="SELECT version();" >/dev/null 2>&1
RESULT=$?
echo DATABASE=${DB_NAME} RESULT=${RESULT}
#

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

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.


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

shorter version


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

The other solutions (which are fantastic) miss the fact that psql can wait a minute or more before timing out if it can't connect to a host. So, I like this solution, which sets the timeout to 3 seconds:

PGCONNECT_TIMEOUT=3 psql development -h db -U postgres -c ""

This is for connecting to a development database on the official postgres Alpine Docker image.

Separately, if you're using Rails and want to setup a database if it doesn't already exist (as when launching a Docker container), this works well, as migrations are idempotent:

bundle exec rake db:migrate 2>/dev/null || bundle exec rake db:setup

참고URL : https://stackoverflow.com/questions/14549270/check-if-database-exists-in-postgresql-using-shell

반응형