HowTo: Use Oracle / MySQL SQL Commands In UNIX Shell Scripts

You can use Oracle/MySQL SQL commands in UNIX shell scripts by using the sqlplus or mysql command-line utilities. These utilities allow you to execute SQL commands from a shell script and get the output back into the script for further processing.

Here’s an example of using sqlplus to execute a simple SQL query and store the result in a shell variable:

#!/bin/sh
sql_result=$(echo "SELECT COUNT(*) FROM employees;" | sqlplus -s user/password@database)
echo "There are $sql_result employees in the database."

In this example, the sqlplus utility is used to execute the SQL query SELECT COUNT(*) FROM employees;. The -s option suppresses the display of SQL*Plus banner, prompts, and echoing of commands. The result of the query is stored in the shell variable sql_result and then displayed in a message.

Similarly, here’s an example of using mysql to execute a simple SQL query and store the result in a shell variable:

#!/bin/sh
sql_result=$(echo "SELECT COUNT(*) FROM employees;" | mysql -s -N -u user -ppassword -h database)
echo "There are $sql_result employees in the database."

In this example, the mysql utility is used to execute the SQL query SELECT COUNT(*) FROM employees;. The -s option suppresses the display of column headings, and -N option turns off column name display. The result of the query is stored in the shell variable sql_result and then displayed in a message.

Note that in both examples, the SQL query is passed to the respective command-line utility via a pipe (|) from the echo command. You can substitute any SQL query you like, and use the shell variable to store and process the result in the script.

Leave a Comment