DBA Tips Archive for Oracle


SELECTing a value from a table into a Unix variable

by Jeff Hunter, Sr. Database Administrator

You can select a value from a database column directly into a Unix shell variable.

Look at the following shell script examples:

VALUE=`sqlplus -silent "/ as sysdba" <<END
set pagesize 0 feedback off verify off heading off echo off
select max(sequence#) from v\\\$log_history;

if [ -z "$VALUE" ]; then
    echo "No rows returned from database"
    exit 0
    echo "Max Sequence Number: $VALUE"

Max Sequence Number: 49
Second example, using the SQL*Plus EXIT status code:
sqlplus -s > junk1 "/ as sysdba" <<EOF
column num_tables new_value num_tables format 9999
select count(*) num_tables from dba_tables;
exit num_tables
echo "Number of tables: $?"

Number of tables: 97
Yet another example, only this time we will read multiple values from SQL*Plus into shell variables.

sqlplus -s "/ as sysdba" |&     # Open a pipe to SQL*Plus

print -p -- 'set feedback off   linesize 500   echo off'
print -p -- 'set pause off      pagesize 0     verify off'
print -p -- 'set heading off    term off       timing off'
print -p -- "set sqlprompt ''"

print -p -- "select sysdate from dual;"
read  -p SYSDATE

print -p -- "select user from dual;"
read  -p USER

print -p -- "select global_name from global_name;"
read  -p GLOBAL_NAME

print -p -- 'select value from v$parameter where name = '\''dispatchers'\'';'
read  -p dispatchers

print -p -- exit

echo "SYSDATE      : $SYSDATE"
echo "USER         : $USER"
echo "dispatchers  : $dispatchers"


Copyright (c) 1998-2018 Jeffrey M. Hunter. All rights reserved.

All articles, scripts and material located at the Internet address of http://www.idevelopment.info is the copyright of Jeffrey M. Hunter and is protected under copyright laws of the United States. This document may not be hosted on any other site without my express, prior, written permission. Application to host any of the material elsewhere can be made by contacting me at jhunter@idevelopment.info.

I have made every effort and taken great care in making sure that the material included on my web site is technically accurate, but I disclaim any and all responsibility for any loss, damage or destruction of data or any other property which may arise from relying on it. I will in no case be liable for any monetary damages arising from such loss, damage or destruction.

Last modified on
Sunday, 05-Sep-1999 00:00:00 EDT
Page Count: 41393