Sub topic 15
Running SQLcl in scripts and automation
This chapter covers running SQLcl without a person at the keyboard: in shell scripts, scheduled jobs, and CI pipelines. It assumes you can already connect with the CONNECT command, have a saved connection from the earlier chapter on saved connections, and know why passwords should not sit in plain text.
What changes when nobody is watching
An interactive session can recover from problems. If a password is wrong, you retype it. If a statement fails, you read the error and move on. A script can't do either of these things, so three behaviors need to be set deliberately:
- Prompts. Any prompt, such as a password request, can leave the job waiting forever.
- Errors. By default SQLcl reports a failed statement and carries on with the next one.
- Exit status. The calling program (cron, a CI runner, a shell) only knows whether the job worked if SQLcl returns a meaningful exit code.
The rest of the chapter deals with these three problems in turn.
Command-line switches for unattended runs
| Switch | Effect |
|---|---|
| `-S` or `-silent` | Suppresses the banner, prompts, and echo of commands, leaving only your output. |
| `-L` or `-logon` | Tries to log in once. If the login fails, SQLcl exits instead of asking again. |
| `/nolog` | Starts SQLcl without connecting, so the script decides how to connect. |
| `@file` | Runs a script file and passes any following words as arguments. |
The basic form from the spine combines the first three:
sql -S -L hr@orclpdb @report.sqlThis line has a weakness. With no password on the command line, SQLcl has to ask for one, which is a prompt a scheduled job cannot answer. The next sections cover how to supply credentials without typing them.
Supplying credentials without exposing them
Do not write hr/MyPassword@orclpdb in a script or on a command line. Command-line arguments show up in the process list (ps) for every user on the host, and they end up in shell history and CI logs. Use one of these approaches instead:
- A saved connection. Create it once, interactively, with
connect -save orclpdb_hr -savepwd .... The script then connects withconnect -name orclpdb_hr. SQLcl keeps the saved password in its connection store in encrypted form, so the script itself holds no secret. - A wallet. For Autonomous Database,
set cloudconfigpoints SQLcl at the wallet zip, and the script connects through a service alias. - A secret fetched at run time. A secrets manager or CI secret store supplies the credential to the job, and the job never writes it to a file or logs it.
Whichever you pick, protect the files involved. Restrict the permissions on the wallet and the SQLcl configuration directory to the account that runs the job, for example chmod 600 on files and chmod 700 on directories.
A complete example
The example has two SQL files and a shell wrapper. The first file, run_report.sql, is the entry point.
whenever sqlerror exit failure rollback
whenever oserror exit failure
connect -name orclpdb_hr
@report.sql &1
exitThe whenever lines come first so that they also cover a failed connection. The second file, report.sql, does the work. It receives the department number as &1.
set feedback off
set heading on
set sqlformat csv
set termout off
spool /tmp/employees_dept.csv
select employee_id, last_name, salary
from employees
where department_id = &1
order by employee_id;
spool off
set termout onThe wrapper script validates its input and passes the exit status upward:
#!/usr/bin/env bash
set -euo pipefail
dept="${1:?usage: run_report.sh DEPARTMENT_ID}"
sql -S /nolog @run_report.sql "$dept"
echo "Report written to /tmp/employees_dept.csv"Run it with ./run_report.sh 50. Because of set -e, if SQLcl exits with a nonzero status, the shell stops before it prints the success message.
Controlling errors and exit codes
The WHENEVER command sets what SQLcl does when something goes wrong:
whenever sqlerror exit failure rollback
whenever oserror exit failureWHENEVER SQLERROR reacts to errors from SQL statements and PL/SQL blocks, such as ORA-00942. WHENEVER OSERROR reacts to operating system problems, such as a spool file that can't be written. exit failure ends SQLcl with a nonzero status. The rollback option undoes uncommitted work before exit. Without a WHENEVER command, SQLcl continues after errors and ends with status 0 when it reaches exit, which makes a broken job look successful.
You can also choose the exit code yourself. For example, exit 3 returns 3 to the caller, so your wrapper can tell apart failure types that you assign different numbers to.
There is a catch with exit sql.sqlcode. It returns the Oracle error number, but on Linux and macOS an exit status is limited to 0 through 255, so the number wraps around. ORA-01017 (error number 1017) becomes 1017 mod 256, which is 249. Use a fixed code such as exit failure unless you have a reason to decode the original number.
Passing arguments and shaping output
Arguments after the script name become substitution variables &1, &2, and so on. In @report.sql 50, &1 is replaced by 50 before the statement runs. Because this is text substitution, never pass untrusted input this way. A value such as 50 or 1=1 would change the meaning of the query. Validate arguments in the wrapper, as the dept check does above. For stricter control, accept only digits:
[[ "$dept" =~ ^[0-9]+$ ]] || { echo "DEPARTMENT_ID must be a number" >&2; exit 2; }Several settings keep script output clean:
set sqlformat csv(alsojson,html, and others) produces machine-readable output without hand-built formatting.set feedback offremoves lines such as "50 rows selected."set termout offhides output from the terminal whilespoolstill writes it to the file. It only takes effect for commands run from a script file, not for commands typed in.set echo offstops SQLcl from printing each command as it runs.
Feeding SQL from a pipe or here-document
You can also send statements to SQLcl through standard input, which suits short one-off jobs:
sql -S /nolog <<'EOF'
whenever sqlerror exit failure
connect -name orclpdb_hr
select count(*) from employees;
exit
EOFQuote the delimiter ('EOF') so the shell does not expand $ characters inside the SQL. Do not put a password in the here-document. It would be exposed in the script file and, depending on your CI system, in the logs.
Logging and diagnosing failed runs
Capture both output streams so a failure leaves evidence:
sql -S /nolog @run_report.sql "$dept" > run.log 2>&1 || {
echo "SQLcl failed, see run.log" >&2
exit 1
}When a scheduled job fails, check these causes first:
- The job runs as a different OS user. Cron often runs as another account, and that account has its own home directory and therefore its own connection store. A connection saved by your login does not exist for the cron user. Run the
connect -savestep as the same user that runs the job. - Wrong working directory.
@report.sqlis resolved relative to where SQLcl starts. Use absolute paths in cron. - A missing
exit. The job never finishes. - A missing environment. Cron has a minimal
PATH, so call SQLcl by its full path, and setJAVA_HOMEif SQLcl cannot find a Java runtime. - A failed login that returns status 0. Without
WHENEVER SQLERROR, a failed connect followed byexitcan end with status 0. Put theWHENEVERline first, beforeconnect, and test it once by deliberately using a wrong connection name.
Exercise
A nightly cron job runs sql -S /nolog @nightly.sql. The script connects with connect -name orclpdb_hr, runs an update, and ends with exit. You saved the connection by hand under your own login, and the job runs as the user batch. The job produces no output, and monitoring says it succeeded. Give two likely causes and one change for each.
Show answer
First, the connection orclpdb_hr was saved in your account's SQLcl connection store, so the batch user has no such connection. Fix it by running connect -save orclpdb_hr -savepwd ... once as batch. Second, the script has no WHENEVER SQLERROR EXIT FAILURE line, so the failed connect and the following errors are ignored and the script still reaches exit with status 0. Fix it by adding whenever sqlerror exit failure rollback as the first line, before connect, so the wrapper and monitoring see a nonzero status.
Exercise
Why is sql -S -L hr/Secret1@orclpdb @report.sql a poor choice for a shared server, and what would you use instead?
Show answer
The password appears in the process list, so other users on the host can read it, and it can also land in shell history and logs. Instead, save the connection once with connect -save name -savepwd ... and connect with connect -name name inside the script, or use a wallet. Restrict the file permissions of the connection store or wallet to the job's account.