通过 Sed 在 Bash 脚本中使用与 heredoc 内容一起分配的变量



我正在尝试用我用heredoc分配的值替换Ansible文件中的一些配置数据。heredoc 数据包含从 Git 检索的值。

最终目标是检索 Git 配置并使用它们的值更新一些 Ansible var 文件。

我不知道如何解决错误

sed: -e expression #1, char 6: unterminated `s' command

Bash 脚本如下所示

update_ansible_config()
{
# Attempt to get the most relevant git configuration (global, local then repo)
GIT_USER=$(git config user.name)
GIT_EMAIL=$(git config user.email)
if [ -z "${GIT_EMAIL}" ] || [ -z "${GIT_USER}" ]; then
echo "Please set up your Git credentials (User and Email)"
exit 1
fi
# Update the ansible vars/all.yml with the Git configuration
# This is the pattern we are looking for
read -r -d '' SEARCH_CONFIG <<EOF
git:
install: '1'
user:
email:.*
name:.*
EOF
# This is the replacement
read -r -d '' REPLACEMENT_CONFIG <<EOF
git:
install: '1'
user:
email: '${GIT_EMAIL}'
name:. '${GIT_USER}'
EOF
CONFIG=test.yml
# Debugging
#echo "${SEARCH_CONFIG}"
#echo "${REPLACEMENT_CONFIG}"
set -x
# Do the replacement
sed -i 's/'"${SEARCH_CONFIG}"'$/'"${REPLACEMENT_CONFIG}"/ "${CONFIG}"
}

也许我把方法过于复杂了,有更好的选择。我想确保我只在 git -> 用户密钥下存在电子邮件和姓名密钥时更新它们。

编辑-

看了@chridd的答案后,我离得更近了。

Bash 输出现在看起来像

+ sed -i 's/git:
install: '''1'''
user:
email:.*
name:.*$/git:
install: '''1'''
user:
email: '''foo@bar'''
name: '''Foo Bar'''/' test.yml
sed: -e expression #1, char 6: unterminated `s' command

我仍然做错了什么。另外,我不需要使用复杂的脚本来获取 Git 配置(更新(

问题是它在哪里说$(echo "${SEARCH_CONFIG}").echo在其输出后输出一个换行符,这意味着如果$SEARCH_CONFIG是"foo",$REPLACEMENT_CONFIG是"bar",那么sed尝试执行的命令看起来像

s/foo
/bar
/

sed将其解释为三个单独的命令,因为它是三行,并抱怨s/foo不是一个完整的命令。 在这种情况下,echo是不必要的;只需直接使用${SEARCH_CONFIG}即可echo

sed -i 's/'"${SEARCH_CONFIG}"/"${REPLACEMENT_CONFIG}"/ "${CONFIG}"

如果你特别关心它位于行尾,那么在正则表达式后面添加一个$(确保引用它(:

sed -i 's/'"${SEARCH_CONFIG}"'$/'"${REPLACEMENT_CONFIG}"/ "${CONFIG}"

最新更新