Understanding <<EOF

Hi all
I stuck with a problem. I want to understand the execution of the below code. Can any one please help me

`sqlplus username/passwd@DB << EOF
set serveroutput on
declare
begin
    sql_query;
end;
/
commit
/
quit
EOF`

My ques is why do we use EOF and how does it help.

This notation is known as heredocs and it allows us enter code with quotation marks, apostrophes and backticks without having to escape them from the shell. The string after the << becomes a close quote string thus facilitating "strinifying" of code or text potentially containing shell interpolatable tokens

You are using the Shell feature known as a "here-document". See the section about "<<" in the manual for your Shell.
The Shell will read up to the terminating word (which in your example is EOF) and present the contents on STDIN to the program which is reading from STDIN (which in your example is sqlplus).

EOF is a popular choice for the terminating word because it happens to be an acronym for End Of File and it does not occur as a command name in any mainstream computer language (including Oracle SQL). You will find on this board that many people use an exclamation mark for the terminating word. Those from a mainframe background sometimes use four asterisks because this was the convention on card-readers.

The code posted is a bit weird because the backticks are not needed or desirable. If the output was to be placed in an environment variable the backticks would be needed. There are a lot of examples on this board.

Personally I prefer to start the script with code to edit the SQL program and place the program into a file, then execute the program as a parameter to sqlplus. This makes debugging so much easier.

@methyl : Can you please show me the sample example for what you are saying in last two lines..

Using your example as an example for Shell purposes. I can't vouch for your sql code as I don't know what you are trying to do (and I don't understand the solidi).
In the commercial world we would not put the username and password on the command line but there is no harm on your private test machine.

# Prepare program
cat <<EOF >myprogram.sql
set serveroutput on
declare
begin
    sql_query;
end;
/
commit
/
quit
EOF
#

# Run program
sqlplus username/passwd@DB @myprogram.sql
1 Like