views:

162

answers:

3

I have the following code in a shell script. This only seems to work when it is not defined in a function. The problematic line is the one containing the "<<". The error message is

"./run: line 210: syntax error: unexpected end of file"

How can I write this correctly within a function?

init_database()
{
    cd ../cfg
    db.sh << ENDC
    $DB_ADMIN

    0
    y
    n
    ENDC

    check_status

    sqlplus $DB_SCHEMA@$DB_NAME < initial_data.sql

    cd -
}
+1  A: 

The end of your "Here document" needs to be unindented, I'm afraid.

Paul Tomblin
You can also use `<<-` as your heredoc operator (instead of `<<`), which will allow leading tabs on your limit string (but not leading spaces).
Plutor
A: 

The ENDC label must be alone in a line without leading/trailing whitspaces.

mouviciel
+5  A: 

There are a number of ways to fix that problem.

1/ Unindent the here document end marker, such as:

cat <<EOF
    hello
    $PWD
EOF

but that will make your code look ugly.

2/ "Indent" the here document begin marker:

cat <<' EOF'
    hello
    $PWD
    EOF

where that bit before the first EOF is exactly the same as the before the second (tab, four spaces, two tabs, whatever). This allows you to keep your nice indenting, although it doesn't expand variables inside the here-document ($PWD doesn't change).

3/ Allow tabs to be stripped from the start of input lines and the end marker.

cat <<-EOF
    hello
    $PWD
    EOF

but there's no way to get tabs into the beginnings of lines.

4/ For your purposes, you can also use:

(   echo "$DB_ADMIN";
    echo "" ;
    echo "0" ;
    echo "y" ;
    echo "n"
) | db.sh
check_status
sqlplus $DB_SCHEMA@$DB_NAME < initial_data.sql
cd -

I believe number 4 is the best option for you. It allows nice lining up of the input, tabs and spaces anywhere in the lines and variable expansion.

paxdiablo