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

How do I call Oracle or MySQL sql statements in UNIX / Linux shell scripts?

You need to use a here document feature supported by sh / bash or ksh. The syntax is as follows:

MySQL: Use SQL Directly In Shell Scripts

#!/bin/sh
user="dbuser"
pass="dbpassword"
db="dbnme"
mysql -u "$user" -p"$pass" "$db" <<EOF
  sql-statement-1;
  sql-statement-2;
EOF

Using Shell Variables In SQL

#!/bin/sh
user="dbuser"
pass="dbpassword"
db="dbnme"
sql="select * from tal_name"
mysql -u "$user" -p"$pass"  <<EOF
  use $db;
  $sql;
EOF

Oracle: Use SQL Directly In Shell Scripts

#!/bin/sh
user="system"
pass="manager"
sqlplus -S $user/$pass <<EOF
  sql-statement-1;
  sql-statement-2;
 exit;
EOF

Using Shell Variables In SQL

#!/bin/sh
user="system"
pass="manager"
var="$1"
sqlplus -S $user/$pass <<EOF
 SELECT * FROM tableName WHERE username=$var;  
 exit;
EOF

You can call sql statements from .sql file itself as follows:

#!/bin/ksh
sqlplus -S system/manager @my_sql_script.sql

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.