加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 用空格缩进heredocs

发布时间:2020-12-15 18:37:17 所属栏目:安全 来源:网络整理
导读:对于个人开发和项目,我使用四个空格而不是标签. 但是,我需要使用heredoc,我不能这样做,而不会破坏缩进流程. 我可以想到的唯一的工作方式是这样的: usage() { cat ' EOF' | sed -e 's/^ //'; Hello,this is a cool program. This should get unindented. Thi
对于个人开发和项目,我使用四个空格而不是标签.
但是,我需要使用heredoc,我不能这样做,而不会破坏缩进流程.

我可以想到的唯一的工作方式是这样的:

usage() {
    cat << '    EOF' | sed -e 's/^    //';
    Hello,this is a cool program.
    This should get unindented.
    This code should stay indented:
        something() {
            echo It works,yo!;
        }
    That's all.
    EOF
}

有没有更好的方法来做到这一点?

让我知道这是否属于Unix/Linux Stack Exchange.

(如果您使用bash 4,请滚动到最后,我认为是纯shell和可读性的最佳组合.)

对于shell脚本,使用选项卡不是偏好或风格的问题;这是语言的定义.

usage () {
    # Lines between EOF are each indented with the same number of tabs
    # Spaces can follow the tabs for in-document indentation
    cat <<-EOF
        Hello,this is a cool program.
        This should get unindented.
        This code should stay indented:
            something() {
                echo It works,yo!;
            }
        That's all.
    EOF
}

另一个选择是避免使用这些文档,而不必使用更多的引号和行延续:

usage () {
    printf '%sn' 
        "Hello,this is a cool program." 
        "This should get unindented." 
        "This code should stay indented:" 
        "    something() {" 
        "        echo It works,yo!" 
        "    }" 
        "That's all."
}

如果您愿意放弃POSIX兼容性,可以使用数组来避免显式的行延续:

usage () {
    message=(
        "Hello,this is a cool program."
        "This should get unindented."
        "This code should stay indented:"
        "    something() {"
        "        echo It works,yo!"
        "    }"
        "That's all."
    )
    printf '%sn' "${message[@]}"
}

以下再次使用这里的文档,但这次用bash 4的readarray命令来填充数组.参数扩展从每个谎言的开始处理去除固定数量的空格.

usage () {
    # No tabs necessary!
    readarray message <<'    EOF'
        Hello,yo!;
            }
        That's all.
    EOF
    # Each line is indented an extra 8 spaces,so strip them
    printf '%s' "${message[@]#        }"
}

最后一个变体:您可以使用扩展模式来简化参数扩展.而不必计算用于缩进的空格数量,只需用选定的非空格字符结束缩进,然后匹配固定的前缀.我用 :. (下面的空格
冒号是为了可读性;它可以删除与前缀模式稍微改变.)

(另外,除此之外,您使用以白色开头的文档定界符的非常好的方法的一个缺点是它阻止您在文档中执行扩展,如果要这样做,您可以要么将分隔符保留为未绑定,或者对您的无标签规则造成一个小小的例外,请使用< -EOF和制表符缩进的关闭分隔符.)

usage () {
    # No tabs necessary!
    closing="That's all"
    readarray message <<EOF
       : Hello,this is a cool program.
       : This should get unindented.
       : This code should stay indented:
       :      something() {
       :          echo It works,yo!;
       :      }
       : $closing
EOF
    shopt -s extglob
    printf '%s' "${message[@]#+( ): }"
    shopt -u extglob
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读