简体   繁体   English

在字符串中扩展bash变量

[英]Expanding bash variable within a string

I am trying to get a variable within a string to expand - its a path:我试图在字符串中获取一个变量来扩展 - 它是一个路径:

/path/to/${variable}/here /path/to/${variable}/这里

  1. The string originates in a json file.该字符串源自 json 文件。
  2. It is subsequently read by jq - at this point I need the expansion to occur.它随后由 jq 读取-此时我需要进行扩展。

Here is the json file:这是json文件:

{
    "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):这是 jq 代码(现在有工作代码 - 谢谢大家):

  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.最初 - 在扩展的 $writeFolder 变量中,可以看到路径,但 ${BUILD_FOLDER} 变量保持未扩展,因为它是按字面意思理解的。 (when I used set -x I could see it was surrounded by single quotes). (当我使用 set -x 时,我可以看到它被单引号包围)。

Eventually used accepted solution from peak to make better use of jq.最终使用了来自峰值的公认解决方案,以更好地利用 jq。

As pointed out in the comments, you'd be much better off making jq do as much work as possible.正如评论中指出的那样,让 jq 做尽可能多的工作会更好。 But to use jq, you'll need to fix the JSON.但是要使用 jq,您需要修复 JSON。 Also, it's not clear to me that you need to compute $numberOfDataFolders at all, so in the interests of simplicity, this is what I'd suggest:另外,我不清楚您是否需要计算 $numberOfDataFolders,所以为了简单起见,我建议这样做:

#!/bin/bash

json_path=input.json

BUILD_FOLDER=mybuildfolder

jq -r --arg bf "$BUILD_FOLDER" '.data_folders[] | sub("\\${BUILD_FOLDER}";$bf)' "${json_path}" |
  while read -r writeFolder
    do
    echo mkdir -p "${writeFolder}"
  done 

Once the input has been fixed, this produces:一旦输入被修复,这将产生:

mkdir -p /Users/me/Desktop/POD_INSTALLS/pod_DB/mybuildfolder/data/table1/
mkdir -p /Users/me/Desktop/POD_INSTALLS/pod_DB/mybuildfolder/data/table2/

Notice also that the -r option circumvents the need to use tr .另请注意, -r 选项避免了使用tr的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM