Home » Infrastructure » Linux » How to reliably capture the result of an SQLPlus query in a Bash script?
How to reliably capture the result of an SQLPlus query in a Bash script? [message #690383] Sun, 03 August 2025 00:06 Go to next message
tristanbailly83
Messages: 2
Registered: June 2025
Junior Member
Hi everyone,

I'm currently working on a Bash script on a Linux server where I need to execute an SQL query using SQLPlus (Oracle), and most importantly, capture the result of that query in a Bash variable for further processing.

For example:

sql
Copier
Modifier
SELECT COUNT(*) FROM my_table;
The goal is to store this result (the count) in a Bash variable like row_count. I’ve tried a few approaches, but I often run into issues with output formatting (extra spaces, headers, blank lines, etc.).

Does anyone have a clean and reliable way to:

Execute a SQL script via SQLPlus from a Bash script,

Capture only the returned value,

Without too much post-processing or output cleaning?

I also came across this article that provides a useful starting point if it helps anyone or sparks ideas for discussion:
https://amine-benkirane.over-blog.com/2011/10/oracle-sqlplus-lancer-un-script-.sql-sous-unix

Thanks in advance for any tips, examples, or shared experiences!
Re: How to reliably capture the result of an SQLPlus query in a Bash script? [message #690384 is a reply to message #690383] Sun, 03 August 2025 01:26 Go to previous message
Michel Cadot
Messages: 68765
Registered: March 2007
Location: Saint-Maur, France, https...
Senior Member
Account Moderator
What about a feedback in your previous topic?

$ cat t.sh
result=`sqlplus -s michel/michel @t.sql`
echo result is: $result

$ cat t.sql
set pagesize 0 heading off feedback off trimout on echo off verify off
select count(*) from dba_data_files;
exit

$ ./t.sh
result is: 8

[Updated on: Sun, 03 August 2025 02:32]

Report message to a moderator

Previous Topic: get value of query sqlplus of bash script
Goto Forum:
  


Current Time: Mon Aug 11 13:12:15 CDT 2025