从shell脚本,我如何检查db2数据库中的表是否存在?

时间:2017-07-19 10:08:38

标签: bash shell unix db2

我正在尝试编写一个脚本,它允许检查db2表是否存在。如果它存在,我将继续触摸文件,如果不存在,那么它必须等待30分钟并尝试在30分钟后检查相同。我怎么能实现这个目标?

#!/bin/sh
db2 "connect to <database> user <username> using <password>"
Variable=`db2 -x "SELECT COUNT(1) FROM SCHEMA.TABLEA WHERE 1=2"`

while read Variable ;
do
  if $Variable=0 
  then touch triggerfile.txt
  else 
  sleep 30
 fi
  done

1 个答案:

答案 0 :(得分:1)

您想继续轮询(不限时间)表格存在吗?使用bash或korn语法可能更具可读性,并避免使用反引号,但这是您的选择。

通常的警告适用,请勿对密码进行硬编码。

除了循环逻辑之外,你可以在循环中尝试这个(bash或ksh语法如下所示),初始化变量以适合自己:

db2 "connect to $dbname user $username using $passwd"
(( $? > 0 )) && print "Failed to connect to database " && exit 1
db2 -o- "select 1 from syscat.tables where tabschema=$schema and tabname=$tabname with ur"
rc=$?
# rc = 0 : the table exists in that schema
# rc= 1  : the table does not exist
(( rc == 1 )) && touch triggerfile.txt
# rc >= 2 : some warning or error, need to investigate and correct
(( rc >= 2)) && print "problems querying syscat.tables" && exit 1
db2 -o- connect reset