I am trying to get a variable within a string to expand - its a path:
/path/to/${variable}/here
- The string originates in a json file.
- It is subsequently read by jq - at this point I need the expansion to occur.
Here is the json file:
{
"server_1":{
"tag": "storage_1",
"user": "me",
"sshKey": "/Users/me/.ssh/id_rsa",
"target_folder": "/Users/me/Desktop/",
"pubIp": "127.0.0.1",
"data_folders": [
"/Users/me/Desktop/POD_INSTALLS/pod_DB/${BUILD_FOLDER}/data/table1/",
"/Users/me/Desktop/POD_INSTALLS/pod_DB/${BUILD_FOLDER}/data/table2/"
]
}
}
Here is the jq code (now with working code - thanks all):
writeFolder=$(jq -r --arg bf "${BUILD_FOLDER}" '.server_'${id}'.data_folders[] | sub("\\${BUILD_FOLDER}";$bf)' "${json_path}")
for folder in $writeFolder
do
ssh -q -o ForwardX11=no -i ${sshKey} ${user}@${pubIp} "mkdir -p ${folder}"
done
Originally - within the expanded $writeFolder variable, the path could be seen but the ${BUILD_FOLDER} variable remained unexpanded as it was taken literally. (when I used set -x I could see it was surrounded by single quotes).
Eventually used accepted solution from peak to make better use of jq.
data_folders, so are you planning to do2-3and get-1for the value ofnumberOfDataFolders?data_foldersis a sibling, not a member, ofserver_1.jq, avoiding shell interpolation and pipelines. For example,numberOfDataFolders=$( jq --arg id "$id" '.["server_" + $id].data_folders | length - 3').eval expandedString="$stringWithVariableInside".