【问题标题】:Pass Array Elements To Heredoc将数组元素传递给 Heredoc
【发布时间】:2019-05-30 11:52:38
【问题描述】:

我正在尝试将数组元素传递给heredoc,目标是生成一个文件,例如:

declare -a box=("element1" "element2" "element3")

cat > test.txt <<-EOF
some text, insert first element
some text, insert second element
some text, insert third element
EOF

这可能吗?,我怎样才能做到这一点?

【问题讨论】:

    标签: linux bash heredoc


    【解决方案1】:

    您可以使用$(..) 嵌套循环:

    declare -a box=("element1" "element2" "element3")
    
    cat > test.txt <<-EOF
    Greetings,
    
    Here are the elements you wanted:
    $(
        for s in "${box[@]}"
        do
          echo "some text, $s"
        done
     )
    
    Happy New Year from $USER
    EOF
    

    执行时,会生成一个test.txt,其中包含:

    Greetings,
    
    Here are the elements you wanted:
    some text, element1
    some text, element2
    some text, element3
    
    Happy New Year from myusername
    

    【讨论】:

    • 谢谢,$(..) 有什么作用?
    • 这叫做命令替换。它在$(..) 中运行命令,捕获其标准输出,并将其替换。例如:echo "The time is now $(date)" 将运行date,捕获Thu Jan 3 14:06:27 PST 2019,并将其插入到字符串中
    • 感谢您花时间解释这一点,谢谢。
    • 是否可以使用数组中的字符串元素在循环内动态构建heredoc?
    • heredoc 是一个模板,您可以在其中插入变量和命令的结果。如果您真的没有模板并且想要动态构建所有内容,请不要使用此处的文档。只需编写一个函数以任何顺序输出您想要的任何内容,然后将该函数重定向到您的文件
    【解决方案2】:

    你当然可以

    cat > test.txt <<-EOF
    some text, ${box[0]}
    some text, ${box[1]}
    some text, ${box[2]}
    EOF
    

    【讨论】:

      猜你喜欢
      • 2021-02-10
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      相关资源
      最近更新 更多