bash 多个 heredocs 等

标签 bash shell sh heredoc

我有一个 bash 构建脚本,我(好吧,Jenkins,但这并不重要,这是一个 bash 问题)像这样执行:

sudo -u buildmaster bash <<'END'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
END

现在我想传入一个变量(Jenkins 参数化构建),比如 PLATFORM。问题是,如果我在我的 heredoc 中引用 $PLATFORM,它是未定义的(我使用“END”来避免变量替换)。如果我将“END”变成 END,我的脚本将变得非常不可读,因为我需要使用所有转义符。

所以问题是,是否有一些(简单、可读的)方法将两个 heredocs(一个带引号,一个不带引号)传递到同一个 bash 调用中?我一直在寻找这样的东西

sudo -u buildmaster bash <<PREFIX <<'END'
PLATFORM=$PLATFORM
PREFIX
# previous heredoc goes here
END

希望它能简单地连接起来,但我无法让这两个 heredoc 工作(我猜 bash 不是 Perl)

我的后备计划是创建临时文件,但我希望有一个我不知道的技巧,有人可以教我:-)

最佳答案

在这种情况下,您可以考虑使用 bash 及其 -s 参数:

sudo -u buildmaster bash -s -- "$PARAMETER" <<'END'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
PARAMETER=$1
END

(请注意,您有一个语法错误,您的结束 END 被引用但不应该被引用)。


还有另一种可能性(这样你就有很多选择——如果适用的话,这个可能是最简单的)是导出你的变量,并使用 -E 切换到 sudo 导出环境,例如,

export PARAMETER
sudo -E -u buildmaster bash <<'EOF'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
# you can use PARAMETER here, it's fine!
EOF

沿着这些思路,如果您不想导出所有内容,您可以使用 env 如下:

sudo -u buildmaster env PARAMETER="$PARAMETER" bash <<'EOF'
# do all sorts of crazy stuff here including using variables, like:
ARGS=something
ARGS="$ARGS or other"
# and so forth
# you can use PARAMETER here, it's fine!
EOF

关于bash 多个 heredocs 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28708068/

相关文章:

java如何调用外部unix命令

mysql - mySQL 脚本中的语法错误?

bash - Sed 仅打印至少包含 2 个单词的行

bash - 我应该避免在我的 shell 脚本中使用 bash -c、sh -c 和其他 shell 的等效项吗?

bash - 如何使用 bash 删除一个旧文件夹?

Bash 脚本不太匹配

linux - Shell 脚本文件 (.sh) 不运行,并引发错误

bash - bash 可以生成多个进程并报告成功运行的进程数吗?

bash - 如何在shell脚本中进入文件夹并进行操作

linux - 如何使用curl检查文件是否下载