Bash中管道会导致数据库连接信息丢失
简单化问题
说明该问题前,我们先把它简单化。
有一个sample data,tab.lst:
tab1,col1
tab2,col2
...
以下两段代码的输出是一致的。
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
加入实际需求
我们期望从一个文本文件中取出表名和列名,然后查询该列的最大值,并重设列sequence的起始值。
我们把需求分别填充到上面的两段代码中。得到如下两段代码:
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中可正常执行。
这两段代码唯一的区别仅在于第二段代码在连接数据库后使用了管道。在Bash中管道会导致数据库连接丢失。
--End
Mason
网友评论