Luchko Serega Luchko Serega - 3 months ago 9
Bash Question

String formatting with Bash

I am writing bash script which form json file:

#!/bin/bash

json_string=$(<product.info.json)
echo "$json_string"

vers=%major_version%.%patch_version%
date=`date +%%Y-%%m-%%d:%%H:%%M:%%S`

echo VERSION: $vers
echo DATE: $date

result_string=$json_string
result_string=${result_string/_DATE_/$date};
result_string=${result_string/_VERSION_/$vers};


echo "$result_string" > "User_Part/product.info.json"

json_string=$(<User_Part/product.info.json)
echo "$json_string


it's console out:

[14:09:26][Step 4/4] {
[14:09:26][Step 4/4] "release":{
[14:09:26][Step 4/4] "version":null
[14:09:26][Step 4/4] },
[14:09:26][Step 4/4] "product":{
[14:09:26][Step 4/4] "group":"CMS",
[14:09:26][Step 4/4] "name":"CMS_prod",
[14:09:26][Step 4/4] "version":"_VERSION_"
[14:09:26][Step 4/4] },
[14:09:26][Step 4/4] "application":{
[14:09:26][Step 4/4] "name":"OAPI",
[14:09:26][Step 4/4] "appl_id":"6150",
[14:09:26][Step 4/4] "version":"_VERSION_",
[14:09:26][Step 4/4] "date":"_DATE_",
[14:09:26][Step 4/4] "detail":null,
[14:09:26][Step 4/4] "vcs":{
[14:09:26][Step 4/4] "hash":null,
[14:09:26][Step 4/4] "branch":null
[14:09:26][Step 4/4] },
[14:09:26][Step 4/4] "build":{
[14:09:26][Step 4/4] "number":null,
[14:09:26][Step 4/4] "url":null
[14:09:26][Step 4/4] }
[14:09:26][Step 4/4] }
[14:09:26][Step 4/4] }
[14:09:26][Step 4/4] VERSION: 003.09
[14:09:26][Step 4/4] DATE: 2016-08-23:14:09:26
[14:09:26][Step 4/4] {
[14:09:26][Step 4/4] "release":{
[14:09:26][Step 4/4] "version":null
[14:09:26][Step 4/4] },
[14:09:26][Step 4/4] "product":{
[14:09:26][Step 4/4] "group":"CMS",
[14:09:26][Step 4/4] "name":"CMS_prod",
[14:09:26][Step 4/4] "version":"003.09"
[14:09:26][Step 4/4] },
[14:09:26][Step 4/4] "application":{
[14:09:26][Step 4/4] "name":"OAPI",
[14:09:26][Step 4/4] "appl_id":"6150",
[14:09:26][Step 4/4] "version":"_VERSION_",
[14:09:26][Step 4/4] "date":"2016-08-23:14:09:26",
[14:09:26][Step 4/4] "detail":null,
[14:09:26][Step 4/4] "vcs":{
[14:09:26][Step 4/4] "hash":null,
[14:09:26][Step 4/4] "branch":null
[14:09:26][Step 4/4] },
[14:09:26][Step 4/4] "build":{
[14:09:26][Step 4/4] "number":null,
[14:09:26][Step 4/4] "url":null
[14:09:26][Step 4/4] }
[14:09:26][Step 4/4] }
[14:09:26][Step 4/4] }


DATE was set but VERSION no, I can't understand why. Please help me with this ambiguity.

Maybe there is more beatiful way to do it, script are executed in build agent server in TeamCity.

Answer

it looks like you are trying to perform the _VERSION_ substitution twice, and it seems the first substitution is successful, but by default the bash param expansion you are using will only perform the substitution once, try

result_string=${result_string//_VERSION_/$vers};

this will have the effect of giving the substitution the g flag - in regex speak.

Comments