Home > Blockchain >  How to append extracted multiple values with comma to new variable?
How to append extracted multiple values with comma to new variable?

Time:12-31

#!/bin/bash

HOSTS="dev.com,dev-secret;qa.com,qa-secret"
HOSTNAME=""
SECRET=""


  IFS=';' read -ra host <<<"$HOSTS"
  for i in "${host[@]}"; do
    IFS=',' read -r name secret <<<$i
    HOSTNAME = ${name}
    SECRET = ${secret}
  done

Now I would like the output as:

echo $HOSTNAME should output : "dev.com\,qa.com" 
echo $SECRET should output : "dev-secret\,qa-secret" 

How can I join or append the for loop output in a string?

CodePudding user response:

Your problem is the space after =. With Parameter Expansion you can add \, only when the parameter is filled.

HOSTS="dev.com,dev-secret;qa.com,qa-secret"
HOSTNAME=""
SECRET=""

IFS=';' read -ra host <<<"$HOSTS"
for i in "${host[@]}"; do
  IFS=',' read -r name secret <<<$i
  HOSTNAME ="${HOSTNAME: \,}${name}"
  SECRET ="${SECRET: \,}${secret}"
done

echo "${HOSTNAME}"
echo "${SECRET}"

CodePudding user response:

Without looping, but reading arrays and performing array join:

#!/usr/bin/env bash

hosts="dev.com,dev-secret;qa.com,qa-secret"
hostnames=()
secrets=()

join () {
  printf %s "$1"
  shift
  printf %s "${@/#/\\,}"
}

{
  IFS=',' read -r -d';' -a hostnames
  IFS=',' read -r -a secrets
} <<<"$hosts"

printf 'Hostnames: "%s"\n' "$(join "${hostnames[@]}")"
printf 'Secrets: "%s"\n'  "$(join "${secrets[@]}")"

Output:

Hostnames: "dev.com\,dev-secret"
Secrets: "qa.com\,qa-secret"
  • Related