0

I need to call sqlplus with oracle user sudo to clearly specified DB (env var ORACLE_SID) by one line command. The usual way to do it consists of 2 steps:

$ sudo -u oracle -i
$ ORACLE_SID=DBNAME sqlplus / as sysdba

But I need to do it in one line (to save time, reasonably). I try to do it simply like this:

$ sudo -u oracle -i ORACLE_SID=DBNAME sqlplus / as sysdba

But it seems that sqlplus does not see changing of ORACLE_SID env var and connects to default DB. Also I can not exclude -i sudo option because I need to be sure that all other environment variables initialized perfectly.

How can I run application with sudo and custom environment variable in my case?

2 Answers2

0

Try the following command:

sudo -i su - oracle -c 'ORACLE_SID=DBNAME && sqlplus'

Explanation:

"sudo -i" will take care of the environment variables.
"su - user" will consider the user's environment variables
"-c" -> the command you wish to issue.
Itai Ganot
  • 10,644
  • 29
  • 93
  • 146
  • It works, thanks. How su works here? If I directly call `su - oracle -c '...'` su asks me for a password. But if I use it with sudo as you wrote there is not a password prompt. – Nikita Petrov Mar 02 '18 at 10:37
  • "su" requires you to insert the password of the user you're trying to run the command as. "sudo" requires you to enter your own user password and as long as your user is a member of the sudoers group then you'll be able to run the command as the other user. Also I believe that you've already inserted your "sudo" password once in that terminal session which is why you weren't asked to re-enter the password, but if you run it on a fresh terminal session you will be required to supply your user's password again. – Itai Ganot Mar 02 '18 at 13:53
  • If my answer solves your issue then please feel free to mark it as the solution, thanks. – Itai Ganot Mar 02 '18 at 13:54
  • It pretty solves the described question. Thanks. But now I want to execute a script directly in one step. The problem here is that script cames from stdin and quotes for `-c` option of `su` are the problem. So I need to call sqlplus in this way: `sqlplus -S / as sysdba << EOF EOF`. How can I do it in one line? – Nikita Petrov Mar 06 '18 at 18:39
  • I thoroughly tested the command you suggested. The main problem with it is that user should have sudo rights for root. See my answer below where I posted the nicest way to solve my question. – Nikita Petrov Mar 16 '18 at 10:36
-1

The best way to solve question is to use the following command:

sudo -u oracle -i sh -c "ORACLE_SID=DBNAME sqlplus / as sysdba"

And if we want to pass sql script straightly at one line:

sudo -u oracle -i sh -c "ORACLE_SID=DBNAME sqlplus / as sysdba" <<-EOF
  SELECT 1 FROM DUAL;
EOF