Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to preserve indention and spaces in array of cat <<-EOF

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

         - 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[@]}"?

>Solution :

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
" )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading