Bash中管道會致使數據庫鏈接信息丟失

Bash中管道會致使數據庫鏈接信息丟失
簡化問題

說明該問題前,咱們先把它簡單化。數據庫

有一個sample data,tab.lst:rest

tab1,col1
tab2,col2
...

如下兩段代碼的輸出是一致的。code

while IFS=, read -r tab col
do
  echo "$tab     $col"
done < tab.lst

cat tab.lst | while IFS=, read -r tab col
do
  echo "$tab     $col"
done
加入實際需求

咱們指望從一個文本文件中取出表名和列名,而後查詢該列的最大值,並重設列生成值的起始。it

咱們把需求分別填充到上面的兩段代碼中。獲得以下兩段代碼:table

db2 connect to <db_name> user <user_name> using xxxxxx
while IFS=, read -r tab col
do
  echo "$tab     $col"
  max_id=$(db2 -x "select max($col)+1 from $tab")

  db2 -v alter table $tab alter column $col set generated by default restart with $max_id
done < tab.lst

# 在Bash中,這一段代碼沒有像咱們所指望的那樣正常執行,而是提示「沒有數據庫鏈接」
db2 connect to <db_name> user <user_name> using xxxxxx
cat tab.lst | while IFS=, read -r tab col
do
  echo "$tab     $col"
  max_id=$(db2 -x "select max($col)+1 from $tab")

  db2 -v alter table $tab alter column $col set generated by default restart with $max_id
done

很遺憾,第二段代碼在Bash中不能正常執行,提示「沒有數據庫鏈接」,而在Ksh中可正常執行。select

而這兩段代碼惟一的區別僅僅在於第二段代碼在鏈接數據庫後使用了管道。管道致使數據庫鏈接丟失。數據

相關文章
相關標籤/搜索