Executing multiple commands under as another username within a file in BASH shell

时间:2015-06-25 18:30:07

标签: linux oracle bash

I am attempting to execute a sqlplus command within a file. The file should be able to sudo switch into the oracle user and run the commands needed. The oracle user will need to first source a file with the parameters for the database, then be able to call a sql file from sqlplus.

The script I have is

#!/bin/bash
sudo -iu user oracle -c `
cd /tmp;
. .sourceme;
sqlplus user/password << EOF;
SPOOL logfile.lst;
@runme.sql;
spool off;
exit;
EOF;`

Whether I run the scrupt with sudo or not, it won't give an error. The only thing it will return is the usage for sudo

usage: sudo -h | -K | -k | -L | -V
usage: sudo -v [-AknS] [-p prompt]
usage: sudo -l[l] [-AknS] [-g groupname|#gid] [-p prompt] [-U username] [-u username|#uid] [-g groupname|#gid] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C fd] [-g groupname|#gid] [-p prompt] [-u username|#uid] [-g groupname|#gid] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-r role] [-t type] [-C fd] [-g groupname|#gid] [-p prompt] [-u username|#uid] file ...

I figure that this means that my syntax is probably incorrect. However, without putting the command entirely on one line, I'm not sure how to fix the syntax. I've tried using double quotes around the command, removing the semicolon, and changing the grave symbol to use parenthesis instead. None of these produce any results. Trying it as a one liner and removing the parenthesis and grave marks gives me the usage information as well as a bunch of

./background: line 2: spool: command not found

1 个答案:

答案 0 :(得分:1)

Try using a heredoc:

#!/bin/bash
sudo -iu user oracle <<XXX
cd /tmp;
. .sourceme;
sqlplus user/password << EOF;
SPOOL logfile.lst;
@runme.sql;
spool off;
exit;
EOF;
XXX