I have the following snippet in a bash script:
db2 connect to $DB
var=$(db2 -x "$query" | tr -d " ")
$query holds a select count query, -x just prints out the result of the command with no headers so var would be assigned to a number.
What happens is that $(...) is executed in a subshell and doesn't inherit the connection to DB2 resulting in the "SQL1024N A database connection does not exist. SQLSTATE=08003" message.
I don't know how does the db2 connect command affects the environment.