我正在尝试在 bash 脚本中使用嵌套的 HEREDOC 块。
笔记
- 外部 HEREDOC 是用户以不同用户身份运行命令列表
sudo
- 内部 HEREDOC 正在将常规文本捕获到
cat
文件中。
# 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
当这个脚本运行时,输出是:
/bin/bash:第 229 行:EOF:找不到命令
为什么 bash 认为这EOF
是一个命令而不是 HEREDOC 分隔字符串
- 我不确定行首和限制字符串之间的空格是否重要 - 如果是这样,请告诉我,我会尽力解释
更新:这是脚本的简化版本,其中具有复制和可粘贴的可运行代码 - 似乎会产生相同的错误
#! /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
输出错误为:
/bin/bash:第 22 行:警告:此处文档在第 8 行由文件结尾分隔(需要“VRC”)
答案1
后面有一个空格VRC
。去掉它。