I am trying to format nested HERE document in bash script but I ended up getting errors. This works since I do not format anything. But for a better readability I am trying to format the below function.
function test_func { : ' my test func '
ssh -i /path/to/identity_file $TEST@${IP} << EOF
cd ~/
mkdir -p some_dir
some commands
if [ -f some_quries.sql ]
then
ssh -i /path/to/identity_file $TEST@${IP} << EOSQL
some_queries.sql; some_other_queries.sql;
exit;
EOSQL
fi
exit
EOFWhen I try to format(I tried couple of the options but no luck):
function test_func { : ' my test func ' ssh -i /path/to/identity_file $TEST@${IP} << \EOF cd ~/ some commands if [ -f some_quries.sql ] then ssh -i /path/to/identity_file $TEST@${IP} << \EOSQL some_queries.sql; some_other_queries.sql; exit; EOSQL fi
exit
EOFI have tried with also <<-EOF and <<-EOSQL but I end up getting here-document at line N delimited by end-of-file (wanted 'EOSQL'). Can someone guide me on this?
I guess I also tried this:
EOSQL
fi
exit
EOF 1 1 Answer
You need to use the <<- form, and the indentation must be done with tab characters (not spaces). From man bash:
If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.
Ex. given
$ cat heredoc.sh
#!/bin/bash cat <<EOF1 Hello from level 1 cat <<EOF2 Hello from level 2 EOF2 EOF1then
$ ./heredoc.sh
./heredoc.sh: line 8: warning: here-document at line 3 delimited by end-of-file (wanted `EOF1') Hello from level 1 cat <<EOF2 Hello from level 2 EOF2 EOF1whereas
$ cat heredoc.sh
#!/bin/bash cat <<-EOF1 Hello from level 1 cat <<-EOF2 Hello from level 2 EOF2 EOF1then
$ ./heredoc.sh
Hello from level 1
cat <<-EOF2
Hello from level 2
EOF2 2