I am trying to use nested HEREDOC blocks in a bash script.
Note
- The outer HEREDOC is user to run a list of commands as a different user via
sudo
- the inner HEREDOC is capturing regular text to
cat
into a file.
# run some commands as regular user
sudo -s -u $reg_user << EOF
echo "installing Pathogen plugin manager"
mkdir -p ~/.vim/autoload ~/.vim/bundle && \
curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
# start the nested HEREDOC
#-----------------------------
#
echo "configuring \.vimrc"
cat <<-VRC >> ~/.vimrc
"
"======================================================
" vim core settings
"======================================================
"
" show numbers - to turn off :set nonumber
set number
" always show status bar
set laststatus=2
VRC # limit string to close the inner HEREDOC
echo "more bash commands"
EOF # end the outer HEREDOC - NOTE: this is also the end of the
# entire script itself
When this script runs, the output is:
/bin/bash: line 229: EOF: command not found
Why does bash think this EOF
is a command and not the HEREDOC delimit string
- Im not sure if the white spaces between the beginning of the lines and the limit strings matter - if so let me know and I'll try to explain
update: here is a simplfied version of the script which has copy and pastable runnable code - that seems to produce the same-ish error
#! /bin/bash
# If you want to run this code you need to assign a valid user here
user="non-root user"
# run some commands as regular user
sudo -s -u $user << EOF
echo "installing plugins"
mkdir -p testdir
# start the nested HEREDOC
#-----------------------------
#
echo "configuring \.config_file"
cat <<-VRC >> /tmp/test_vimrc
"
"======================================================
" vim core settings
"======================================================
"
" show numbers - to turn off :set nonumber
set number
" always show status bar
set laststatus=2
VRC
echo "more bash commands"
EOF
output error is:
/bin/bash: line 22: warning: here-document at line 8 delimited by end-of-file (wanted `VRC')
-
in the HEREDOC command is like a switch to tell HEREDOC to ignore tabs , it shouldn't be considered part of the HEREDOC delimiter