如何在shell脚本中即时解释变量?

问题描述:

我正在使用JQ在Shell脚本中读取JSON.在这里,我无法即时解释shell脚本中的变量$ HOME,$ HOST,$ PEMFILE.

I'm reading JSON in a shell script using JQ. Here, I'm unable to interpret the variables $HOME, $HOST, $PEMFILE in my shell script on the fly.

JSON文件:

{
    "script": {
    "install": "${HOME}/lib/install.sh $HOST $PEMFILE",
    "Setup": "${HOME}/lib/setup.sh $HOST $PEMFILE $VAR1 $VAR2"
    }

}

Shell脚本:

#!/bin/bash
examplefile="../lib/example.json"
HOST=ec2-..-...-...-...us-west-2.compute.amazonaws.com
PEMFILE=${HOME}/test.pem

installScript=($(jq '.script.install' $examplefile))
bash "$installScript"

有没有一种方法可以即时解释这些变量而无需修改JSON?

Is there a way I can interpret these variables on the fly without modifying the JSON?

P.S我不想使用eval.

P.S I don't want to use eval.

以下是使用环境

Here is a solution using env and gsub to perform the replacement.

请注意,env要求将变量作为环境变量而不是shell变量进行传递.

Note that env requires the variables to be passed as environment variables as opposed to shell variables.

#!/bin/bash

examplefile="../lib/example.json"
HOST=ec2-..-...-...-...us-west-2.compute.amazonaws.com
PEMFILE=${HOME}/test.pem

export HOST
export PEMFILE
installScript=$(jq -Mr '
   .script.install | gsub("(?<x>[$][{]?\\w+[}]?)"; env[.x|gsub("[${}]+";"")] )
' $examplefile)

echo $installScript

样本输出

/home/runner/lib/install.sh ec2-..-...-...-...us-west-2.compute.amazonaws.com /home/runner/test.pem

在线试用!