【问题标题】:bash multiple heredocs et albash 多个 heredocs 等
【发布时间】:2015-04-26 19:12:35
【问题描述】:

我有一个 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

希望它可以简单地连接,但我无法让两个 heredocs 工作(我猜 bash 不是 Perl)

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

【问题讨论】:

    标签: bash shell sh heredoc


    【解决方案1】:

    在这种情况下,您可以考虑使用 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
    

    【讨论】:

    • 我实际上认为你在这里有更好的答案——我的答案当然是字面问题,但这些做法比字面答案更可取。
    • 这个方法很不错! (我修复了语法错误)
    【解决方案2】:

    将您引用的前缀替换为未引用的完整文档:

    # store the quoted part in a variable
    prefix=$(cat <<'END'
    ARGS=something
    ARGS="$ARGS or other"
    END
    )
    
    # use that variable in building the full document
    sudo -u buildmaster bash <<END
    $prefix
    ...
    END
    

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2015-10-17
      • 2013-07-25
      • 2019-12-10
      • 2017-09-28
      • 2014-03-28
      • 2019-08-31
      • 2012-02-07
      • 1970-01-01
      相关资源
      最近更新 更多