Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script and SQL results

I currently want to extract a value from a SQL command responde

somehting like this:

psql db -c "SELECT COUNT(test) FROM tbTest;"

the result is:

 count
------
 33176
(1 row)

I want to extract the 33176 value... is there any simple way to do this?

like image 779
Killercode Avatar asked Aug 17 '11 13:08

Killercode


3 Answers

Why mucking with the unwanted stuff? Simply use some psql options...

> psql -At -c "SELECT COUNT(test) FROM tbTest;" db
115899
like image 191
A.H. Avatar answered Jan 03 '23 16:01

A.H.


By enclosing the complete shell command in backticks, you can retrieve its result into a shell variable:

#/bin/sh

THECOUNT=`psql -A -t -c 'SELECT COUNT(*) FROM tbTest;' db`
echo "the count = $THECOUNT"
like image 22
wildplasser Avatar answered Jan 03 '23 14:01

wildplasser


If it is always return in that format (expected result on line 3), you can use this:

psql db -c "SELECT COUNT(test) FROM tbTest;" | tail -n 2 | head -n 1

The explanation:

tail -n 2 will get the last 2 line and then processed by head -n 1 which mean, get first 1 line.

like image 23
ariefbayu Avatar answered Jan 03 '23 15:01

ariefbayu