Existing DB2 connection does not work inside a script I connected to the DB2 instance, and I can successfully verify that the connection exists:

db2inst1@hostname:/tmp$ db2 connect

   Database Connection Information

 Database server        = DB2/LINUXX8664 10.5.3
 SQL authorization ID   = DB2INST1
 Local database alias   = DBNAME


However, when I run the following script

db2inst1@hostname:/tmp$ cat test.sh
#!/bin/bash 
db2 connect


the connection seems to disappear:

db2inst1@hostname:/tmp$ ./test.sh 
SQL1024N  A database connection does not exist.  SQLSTATE=08003


I wonder,


What is reason for that?
How to work in scripts with the existing connection?
As @mustaccio points out in the comment, a connection is local to its subshell.

In order to call the shell script in the context of the current shell, source could be used:

db2inst1@hostname:/tmp$ source test.sh

   Database Connection Information

 Database server        = DB2/LINUXX8664 10.5.3
 SQL authorization ID   = DB2INST1
 Local database alias   = DBNAME


Of course, . also works:

db2inst1@hostname:/tmp$ . test.sh

   Database Connection Information

 Database server        = DB2/LINUXX8664 10.5.3
 SQL authorization ID   = DB2INST1
 Local database alias   = DBNAME