8

We are writing a bash script which basically does the job of python dictionary. Below is the code siffet we are using and the expected output.

#!/bin/bash
declare -A serviceTag
serviceTag["source"]="ccr"
declare -A services
services+=( ["dataservice"]="latest" )

serviceTag+=( ["services"]=services )

echo "$serviceTag"

The expected output is

{"source":"ccr","services":{"datasetvice":"latest"}}

But what we are getting is

ccrservices

Can somebody help us in what mistake we are doing here and how can we achieve this using bash and its code?

Regards, Kanthu

  • That and services is just the string services - you need array expansion for that as well. – muru Mar 26 '20 at 11:23
  • Sorry, I didnt get it. Can you pls suggest me the code changes? – Kanthu Canty Mar 26 '20 at 11:30
  • printf '{"%s":"%s","%s":"%s":{"%s":"%s"}}\n' "${!serviceTag[@]}" "${serviceTag[@]}" "${!services[@]}" "${services[@]}" – Jetchisel Mar 26 '20 at 11:31
  • 1
    @jet I reopened it, you can post that as an answer – muru Mar 26 '20 at 11:31
  • Using $avar instead of ${avar[@]} with an array avar refers to its first entry, not to the whole array, and you are NOT getting that output (ccrservices) from the code you have posted. But, as already said, bash's arrays are unidimensional, so that will not work, anyways. –  Mar 27 '20 at 02:02
  • Thaks Mosvy for your comment. If its an unidimensional, then I will have to look for other options on scripting. – Kanthu Canty Mar 27 '20 at 04:03

3 Answers3

2

According to the GNU project's Bash reference manual, Bash's arrays are one-dimensional, whether they be indexed or associative. That means you can't nest them. Sorry to be the bearer of bad news, but I don't think what you're trying to do is possible.

0

Not sure but you can try.

printf '{"%s":"%s","%s":"%s":{"%s":"%s"}}\n' "${!serviceTag[@]}" "${serviceTag[@]}" "${!services[@]}" "${services[@]}" 
Jetchisel
  • 1,264
0

This isnt a task thats appropriate for shell scripting. Do yourself a favor, and use a programming language for this task. For example with PHP:

<?php
$services = ['dataservive' => 'latest'];
$serviceTag['source'] = 'ccr';
$serviceTag['services'] = $services;
# example 1
print_r($serviceTag);
# exmaple 2
echo json_encode($serviceTag), "\n";

Result:

Array (
   [source] => ccr
   [services] => Array (
      [dataservive] => latest
   )
)
{"source":"ccr","services":{"dataservive":"latest"}}
Zombo
  • 1
  • 5
  • 44
  • 63