jsonbashshell

how can i append a file into another file with a suitable format using script shell


I have this json file template.json

{
    "PTF_INSTALL_DATE": " 2020-03-31 09:12:10",
    "PTF_CONTENT": [
      {
        "NAME": "api_batch_API",
        "CHECKED": "api_batch_NOT_SELECTED",
        "VERSION": "G02R00C13_c14"
      }
    ]
  }

And this file historique.json,It created by script bash , I call the script in Jenkinsfile

  [
   {
        "PTF_INSTALL_DATE": " 2020-03-31 09:12:10",
        "PTF_CONTENT": [
          {
            "NAME": "api_batch_API",
            "CHECKED": "api_batch_NOT_SELECTED",
            "VERSION": "G02R00C13_c14"
          }
        ]
     }
   ]

So when I do a build in jenkins an element has added in the last of file historique.json like below:

[
    {
           "PTF_INSTALL_DATE": " 2020-03-31 09:12:10",
           "PTF_CONTENT": [
             {
                "NAME": "api_batch_API",
                "CHECKED": "api_batch_NOT_SELECTED",
                "VERSION": "G02R00C13_c14"
              }
            ]
         }
]
{
        "PTF_INSTALL_DATE": " 2020-03-31 09:12:10",
        "PTF_CONTENT": [
          {
            "NAME": "api_batch_API",
            "CHECKED": "api_batch_NOT_SELECTED",
            "VERSION": "G02R00C13_c14"
          }
        ]
  }

And ect. So my question is how can I formatted the historique file to be like below:

 [
      {
           "PTF_INSTALL_DATE": " 2020-03-31 09:12:10",
           "PTF_CONTENT": [
                  {
                    "NAME": "api_batch_API",
                    "CHECKED": "api_batch_NOT_SELECTED",
                    "VERSION": "G02R00C13_c14"
                  }
        ]
     },

    {
            "PTF_INSTALL_DATE": " 2020-03-31 09:12:10",
            "PTF_CONTENT": [
              {
                "NAME": "api_batch_API",
                "CHECKED": "api_batch_NOT_SELECTED",
                "VERSION": "G02R00C13_c14"
              }
       ]
    }
]

This my script script.sh

#!/bin/bash

a=$(cat template.json)

if [ -e $WORKSPACE/project/historique.json ];
then
  cat template.json >> historique.json
else
  cat <<-EOF > historique.json
   [
    $a
   ]
EOF
fi

PS: The file template.json change at each build in jenkins

The problem is the command after "then". Any suggestion please??(And sorry for my English)


Solution

  • After oguz ismail and shawn response the script file become like that:

    #!/bin/bash
    
    a=$(cat template.json)
    
    if [ -e $WORKSPACE/project-CRMGP/historique.json ];
    then
      jq '. + [input]' historique.json template.json > historique1.json 
    else
      cat <<-EOF > historique.json
       [
        $a
       ]
    EOF
    fi
    
    mv historique1.json historique.json