1

I am writing the following script:

#!/bin/bash

db2 connect to andres
a=$(db2 connect)
echo $a

b=$(db2 connect && echo $?)
echo $b

c=$(db2 connect ; echo $?)
echo $c

d=$(db2 connect)
echo $d

What I am doing is to execute multiples commands inside a subshell by using the current established connection; however, the connection is only identified as connected when only a db2 command is issued. If I use a pipe or multiple commands in the subshell, the connection is not identified. Why?

$ ./test

   Database Connection Information

 Database server        = DB2/LINUXX8664 10.5.5
 SQL authorization ID   = DB2INST1
 Local database alias   = ANDRES

Database Connection Information Database server = DB2/LINUXX8664 10.5.5 SQL authorization ID = DB2INST1 Local database alias = ANDRES
SQL1024N A database connection does not exist. SQLSTATE=08003
SQL1024N A database connection does not exist. SQLSTATE=08003 4
Database Connection Information Database server = DB2/LINUXX8664 10.5.5 SQL authorization ID = DB2INST1 Local database alias = ANDRES

As you can see, the connection is still active after the last statement.

AngocA
  • 7,655
  • 6
  • 39
  • 55
  • Try double quoting your echo variable (eg. `echo "$a"`)... – l'L'l Apr 18 '17 at 16:43
  • @I'L'I This does not solve the problem of not detecting the connection when two commands are issued in the subshell. – AngocA Apr 18 '17 at 16:56
  • 1
    Because Bash optimizes a single command in parentheses to _not_ run in a subshell. You can easily verify that by comparing `(ps -f) | grep ` and `(ps -f | grep )` – mustaccio Apr 18 '17 at 17:24

1 Answers1

1

Excerpt from: https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.7.0/com.ibm.db2.luw.admin.cmd.doc/doc/r0010412.html

The first db2 invocation starts the back-end process. All front-end processes with the same parent are serviced by a single back-end process, and therefore share a single database connection

In the cases of $b and $c they are running as single command (as pointed out by mustaccio), it fails because only pipe and redirect are supported in db2 CPL. To prove that your approach is still achievable, you may want to consider using here string in the variable assignments:

b=$(echo $? <<< $(db2 connect))

or, display like all the others:

b=$(paste <(db2 connect) <(echo $?))
Unwastable
  • 629
  • 4
  • 5