當 SQL 查詢無法傳回任何內容時,我該如何告訴 shell 傳回「false」?

當 SQL 查詢無法傳回任何內容時,我該如何告訴 shell 傳回「false」?

這可能與 SQL 沒有任何關係,因為我確信其他命令也會執行此操作。

在本例中,我透過 shell 發送查詢,如果查詢與任何表格都不匹配,則實際上不會返回任何內容,甚至不會返回回車符。

在這種情況下,如何編寫 shell 腳本來回傳a 0or ?false

這是我的範例命令,它產生了我的問題:

mysql -u Popey --password='Misses Jono' -s -N --disable-column-names -e 
"select term_id from shuttleworth.wp_terms where name = 'nonExistentName' LIMIT 1;"

答案1

-v詳細模式的選項應該會給你更多的輸出。我現在無法嘗試此操作,因為我沒有運行 SQL 伺服器。

答案2

我的表弟向我提供了這個解決方案。測試了一下,它有效。

單線:

response=$(mysql -u popey --password='Misses Jono' -s -N --disable-column-names -e "select term_id from shuttleworth.wp_terms where name = 'non-existent-name' LIMIT 1;") && if [ -z "$response" ]; then echo false; else echo $response; fi`

分解:

response=
    $(mysql 
      -u popey 
      --password='Misses Jono' 
      -s -N --disable-column-names 
      -e 
          "SELECT term_id 
           FROM shuttleworth.wp_terms
           WHERE name = 'non-existent-name' 
           LIMIT 1;"
      ) 
&& if [ -z "$response" ]; 
   then echo false; 
   else echo $response; 
   fi

相關內容