2013-12-12 53 views
0

我正在嘗試編寫一個bash腳本,用於創建並設置postgres數據庫(如果它尚不存在)。繼this,我得這個腳本:在bash中測試返回值

if [ `psql -l | grep mydb | wc -l` -eq 1] 
then 
    echo "Database exists" 
else: 
    echo "Creating database" 
    ... 
fi 

但它總是與"Database exists"返回,而不管數據庫是否存在與否。我也試過[ "` psql -l | grep mydb | wc`" == "1" ],但它給出了相同的結果。我究竟做錯了什麼?

編輯psql -lpsql -l | grep mydb輸出是:

$ psql -l 
             List of databases 
    Name | Owner  | Encoding | Collate | Ctype | Access privileges 
------------+--------------+----------+-------------+-------------+----------------------- 
geoserver | adminhgv7rj4 | UTF8  | en_US.UTF-8 | en_US.UTF-8 | 
postgres | postgres  | UTF8  | en_US.UTF-8 | en_US.UTF-8 | 
project_db | gis_group | UTF8  | en_US.UTF-8 | en_US.UTF-8 | 
template0 | postgres  | UTF8  | en_US.UTF-8 | en_US.UTF-8 | =c/postgres   + 
      |    |   |    |    | postgres=CTc/postgres 
template1 | postgres  | UTF8  | en_US.UTF-8 | en_US.UTF-8 | =c/postgres   + 
      |    |   |    |    | postgres=CTc/postgres 
(6 rows) 
$ psql -l | grep mydb 
$ 
+0

'psql -l'的輸出是什麼?和'psql -l | grep mydb'? – fedorqui

+0

如果你只是想測試'grep'是否找到了某個東西,你應該使用'if psql -l | grep -q mydb;那麼...'。 – Alfe

+0

@fedorqui我已經手動執行了這些操作,以確保它們能夠輸出正確的結果。 'psql -l |的輸出grep mydb | wc -l是'0'。如果我手動創建數據庫,它是'1',如果我放棄它,它會回到'0'。 – aquavitae

回答

3

如果你只是想測試的grep是否發現了什麼或沒有,你應該使用

if psql -l | grep -q mydb 
then 
    … 
2

由你提到的問題包括不要求多個管道,而且似乎更簡單的方法。

你可以說:

(createdb mydb || { echo "creating.." ; false; }) && echo "database exists" 

這基本上等同於說:

if ! createdb mydb; then 
    echo "Creating database"; 
else 
    echo "Database exists" 
fi 
+0

感謝您的建議,但是如果數據庫不存在,我需要運行一系列命令,而且我無法像這樣包裝它們。 – aquavitae

+0

@aquavitae我不確定你的意思是「我不能把它們全部包裝好」 - 你可以在任何塊中插入多條語句。 – devnull

+0

哦,你的意思是使用第二種形式,並在'echo'下面加入額外的代碼。是的,這可以工作! – aquavitae