Reputation: 11
I have written a shell script for connecting to a DB2 database. This script lists out the databases on DB2 server and connects to the database after user enters the desired database name. But after the script runs with a successful db connection info, when I try to run a command against the database it says that the database connection does not exist. SQLSTATE=08003
#!/bin/bash
#
#DBA DB2 Script: DB connection script-connectdb
#Created By : Ashish Verma
#Creation Date : 04/27/2019
#
#Purpose: This script connects to and activates the database
#printf "Below is the list of databases"
DBLIST=`db2 list db directory | grep -i alias | awk '{print $4}'`#This stores all the available databases in DBLIST
USER=`whoami`
echo "Following are the list of available database(s)"
echo "----------------------------------------------"
for db in $DBLIST; do
echo $db#Present the user will all available databases to choose and input
done
printf "\nEnter the name of the database you wish to connect to: "
read CHOICE#User enters tha db name
DB=`db2 "connect to $CHOICE user $USER"`##connection to database is made and output stored in variable DB
if [ -z "$(echo $DB | awk '{print $18}')" ]; then
printf "Database connection failed! Please check the below error: "#Prints if database is not connected to
printf "\n$DB\n"
else
printf "\nYou are connected to database $DB\n"#Prints successful connection
fi
#End of Script
After running the above script a database connection is made successfully and line "You are connected to database $DB" is printed". Any command that is run against the database from the shell should be successful. Eg: db2 list tablespaces; But even after a successful database connection is made in the above script, when I try to run a command against the database, it says that the database connection does not exist and I have to gain fire the "db2 connect to database db_name" command from the shell to manipulate the database. Can someone please help me why do I need to fire the connect to database command even after running the above script successfully?
Upvotes: 1
Views: 2670
Reputation: 7693
What I recommend is to establish the connection as a command directly in your code and not as part of the assignment of a variable that creates a subshell.
db2 connect to $CHOICE user $USER
After that, just check the error code and not the generated output.
if [ $? -ne 0 ] ; then
echo error
exit 1
fi
If you really need to process the output, then redirect the db2 output to a file (even a tempfile) and process the output via reading the file (cat).
Never take the output to a variable via a subshell, like
`db2 ...`
or $(db2 ...)
.
Upvotes: 2