Trying to get 2 character version from database table sysibm.sysversions. This is working independently with:
db2 -x "select versionnumber from sysibm.sysversions where UPPER(authid) = UPPER('db2dev')" | sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//' | head -c2
This gives the result:
11
Trying to incorporate this into a script is giving strange results
db2 connect to sample
_dbversion=$(db2 -x "select versionnumber from sysibm.sysversions where UPPER(authid) = UPPER('${_dbuser}')" | sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//')
echo -e "${_dbversion}"
This gives connection errors
SQL1024N A database connection does not exist. SQLSTATE=08003
I can get around this by either performing the grep outside of select
db2 connect to sample
_dbversion=$(db2 -x "select versionnumber from sysibm.sysversions where UPPER(authid) = UPPER('${_dbuser}')")
_dbversion_head=$(echo -e ${_dbversion1} | sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//' | head -c2)
echo -e "${_dbversion_head}"
Or connecting within the brackets
_dbversion=$(db2 -x connect to sample; db2 -x "select versionnumber from sysibm.sysversions where UPPER(authid) = UPPER('${_dbuser}')" | sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//' | head -c2)
Is it possible to have the connect scope be extended when using grep/sed ?
Pipe causes db2 -x "select..."
to execute in a subshell, while the connection remains local to the parent shell.
You can simply put both connect
and select
into a file (or even here-document) to run them as a script and thus guarantee that both execute in the same session:
db2 -x <<EOF | sed -e ...
connect to yourdb
select versionnumber ...
EOF
See also related question.