0

我希望有人可以帮助将 db2 命令的输出应用到一个变量,以便稍后在脚本中使用。

到目前为止,我在...

db2 "connect to <database> user <username> using <password>"

while read HowMany ;
do
  Counter=$HowMany
  echo $HowMany
done < <(db2 -x "SELECT COUNT(1) FROM SYSCAT.COLUMNS WHERE TABNAME = 'TableA' AND TABSCHEMA='SchemaA' AND GENERATED = 'A'")

当尝试$Counter在 while 循环之外引用时,它SQL1024N A database connection does not exist. SQLSTATE=08003会像echo $HowMany

我尝试了另一种使用管道的方法,这使得$HowMany显示正确的值,但由于那是一个子外壳,它后来丢失了。

如果可能的话,我宁愿不使用临时文件并删除它们,因为如果脚本随时中止,我不喜欢遗留文件。

4

2 回答 2

2

Linux 和 UNIX 上的 DB2 CLP 可以在不丢失其数据库连接上下文的情况下处理命令替换,从而可以将查询结果捕获到本地 shell 变量中或将其视为内联文本块。

#!/bin/sh
# This script assumes the db2profile script has already been sourced

db2 "connect to <database> user <username> using <password>"

# Backtick command substitution is permitted
HowMany=`db2 -x "SELECT COUNT(1) FROM SYSCAT.COLUMNS WHERE TABNAME = 'TableA' AND TABSCHEMA='SchemaA' AND GENERATED = 'A'"`

# This command substitution syntax will also work
Copy2=$(db2 -x "SELECT COUNT(1) FROM SYSCAT.COLUMNS WHERE TABNAME = 'TableA' AND TABSCHEMA='SchemaA' AND GENERATED = 'A'")

# One way to get rid of leading spaces
Counter=`echo $HowMany`

# A while loop that is fed by process substitution cannot use 
# the current DB2 connection context, but combining a here 
# document with command substitution will work
while read HowMany ;
do
  Counter=$HowMany
  echo $HowMany
done <<EOT
$(db2 -x "SELECT COUNT(1) FROM SYSCAT.COLUMNS WHERE TABNAME = 'TableA' AND TABSCHEMA='SchemaA' AND GENERATED = 'A'")
EOT
于 2015-02-06T06:58:29.720 回答
0

正如您所发现的,一个 shell 中的 DB2 连接对子 shell 不可用。您可以使用子 shell,但必须将CONNECT语句放在该子 shell 中。

所以它更像是一个简单的重写,并且不使用子shell:

db2 "connect to <database> user <username> using <password>"

db2 -x "SELECT COUNT(1) FROM SYSCAT.COLUMNS WHERE TABNAME = 'TableA' AND TABSCHEMA='SchemaA' AND GENERATED = 'A'" | while read HowMany ; do
    Counter=$HowMany
    echo $HowMany
done
于 2015-02-05T17:35:21.037 回答