开发者

expr, eval or test to check for returned value

I have a simple database query I wrapped in my bash script.

In case my query retrieves one row, I want to do several things. If my query retrieves zero rows, I want to terminate my script gracefully.

What is the best way to check if my script retrieves zero rows? Can you please provide some pointers?

Th开发者_Go百科ank you.


Here's a working bash script to get number of rows from the DB. Just pass the variables and replace FROM part of the sql with yours.

#!/bin/bash
NUMROWS=`$ORACLE_HOME/bin/sqlplus -s $DBUSER/$DBPASSWORDd@//$DBHOST:$DBPORT/$ORACLE_SID   << EOF
WHENEVER SQLERROR EXIT FAILURE ROLLBACK
SET HEADING OFF
SET FEEDBACK OFF
SET PAGES 0
select count(*) from dual;
exit success
EOF`
echo $NUMROWS

HINT: Replace the last line echo $NUMROWS with exit $NUMROWS and your script will exit gracefully if there are no records. Wrap it in a bash if statement if you want to do other things, as below.

if [ $NUMROWS -lt 1 ]; then
  #exit gracefully
  exit 0; 
fi

# do something


Let's call the command do_it. Then, the simplest thing that comes to mind is:

do_it | while read x; do 
    # do whatever you want ...
done

In this case, that block won't be run if there are no results


I figured it out: the trick is to use /dev/null.

#!/bin/bash
DB2INSTANCE=db2inst1
BIN="/users/db2inst1/sqllib/bin"
OUT=`${BIN}/db2 connect to myschema > /dev/null 
${BIN}/db2 -x "SELECT CURRENT_DATE FROM SYSIBM.SYSDUMMY1 WITH UR"
${BIN}/db2 quit > /dev/null
`
echo $OUT

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜