Home > Back-end >  How to preserve indention and spaces in array of cat <<-EOF
How to preserve indention and spaces in array of cat <<-EOF

Time:08-14

Can you see why the following is removing indention and spaces, when added to array:

show_config(){

    HOSTS_LIST=("1.2.3.4" "5.6.7.8")

    TARGET_ENDPOINTS=()

    for index in "${!HOSTS_LIST[@]}"; do

      HOST="${HOSTS_LIST[index]}"

ENDPOINT=$(cat <<-EOF
              - endpoint:
                  health_check_config:
                    port_value: 6443
                  address:
                    socket_address:
                      address: $HOST
                      port_value: 60051
EOF
)
  # echo "$ENDPOINT"
  TARGET_ENDPOINTS =( $ENDPOINT )
done

  echo "${TARGET_ENDPOINTS[*]}"
}

I get:

- endpoint: health_check_config: port_value: 6443 address: socket_address: address: 1.2.3.4 port_value: 60051 - endpoint: health_check_config: port_value: 6443 address: socket_address: address: 5.6.7.8 port_value: 60051

Expected:

         - endpoint:
              health_check_config:
                port_value: 6443
              address:
                socket_address:
                  address: 1.2.3.4
                  port_value: 60051
          - endpoint:
              health_check_config:
                port_value: 6443
              address:
                socket_address:
                  address: 5.6.7.8
                  port_value: 60051

I can see, if I echo each item in the array in the loop it prints out each element as:

          - endpoint:
              health_check_config:
                port_value: 6443
              address:
                socket_address:
                  address: 1.2.3.4
                  port_value: 60051

But when I add items to the array TARGET_ENDPOINTS =( $ENDPOINT ) the indentions and spaces is removed when echoing out the array echo "${TARGET_ENDPOINTS[@]}"?

CodePudding user response:

You preserve the newlines by quoting $ENDPOINT. You probably want a newline after the last line too, so this should do it:

  TARGET_ENDPOINTS =( "$ENDPOINT
" )

CodePudding user response:

I'd recommend using a tool like yq to generate the desired YAML. Something like

show_config(){
    echo '["1.2.3.4", "5.6.7.8"]' | yq -y '[.[] | {endpoint: {health_check_config: {port_value: 6443}, address: {socket_address: {address: ., port_value: 60051}}}}]'
}
  •  Tags:  
  • bash
  • Related