Home > dba, unix > How to reuse connection in shell

How to reuse connection in shell

It is Friday, I wanted to give my readers some stuff for the week-end ;-)

Imagine that piece of code :

countlines() {
  c=$(sqlplus -s /nolog <<EOF | grep -v Connected
connect scott/tiger
set feed off head off
select count(*) from $1;
EOF
)
  echo there are $c lines in $1
}

countlines EMP
countlines DEPT

I can run this

time ./script1
there are 14 lines in EMP
there are 4 lines in DEPT

real    0m0.46s
user    0m0.06s
sys     0m0.09s

Sounds like a regular shell script. How could we optimize the countlines function? Well, we could create the connection only once and use coprocess pipe (with |& that is pipe ampersand)

sqlplus -s /nolog |&

print -p "connect scott/tiger"

read -p line
if [ $line != Connected. ]
then
  exit 1
fi

print -p "set feed off head off"

countlines() {
  print -p "select count(*) from $1;"
  read -p c
  echo "there is $c lines in $1"
}

countlines EMP
countlines DEPT

print -p disconnect

A two-ways pipe is opened with sqlplus. There is only one connect, and one disconnect.

Let’s check the performance :

$ time ./script2
there is 14 lines in EMP
there is 4 lines in DEPT

real    0m0.23s
user    0m0.00s
sys     0m0.01s

About twice as fast! Note the “Connected” output may not exist in recent version of sqlplus in silent mode. If you have a script that generates hundreds of connections, or which create a connection every 5 seconds or so, think about it :)

Enjoy your week-end

Bookmark and Share

  1. May 18th, 2009 at 11:11 | #1

    This is why I’ll always prefer Korn shell to Bash, even though most *nix distributions have only the ancient ksh 88 rather than ksh 93.

    zsh seems to support coprocesses as well but I haven’t experimented with it.

  2. Chen Shapira
    May 19th, 2009 at 23:27 | #2

    Hey, that’s a great tip! I’ll keep this idea in mind (and not just for the weekend..)

  3. May 26th, 2009 at 09:17 | #3

    @William Robertson
    William, thanks for the info, I did not even know it was a ksh feature ;-)

  4. goo321
    April 20th, 2010 at 05:29 | #4

    The no timeout in read greatly annonys me (old version of ksh)

  5. April 20th, 2010 at 10:01 | #5

    I did not know read in bash had a timeout.

    I do not like read in bash however, because

    echo x|read a; echo $a

    does not work

  1. May 22nd, 2009 at 18:44 | #1
  2. August 11th, 2009 at 09:16 | #2