将bash变量传递给jq

将bash变量传递给jq

本文介绍了将bash变量传递给jq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个脚本来从file.json中检索某些值.如果我将值提供给jq select,它将起作用,但是该变量似乎不起作用(或者我不知道如何使用它).

I have written a script to retrieve certain value from file.json. It works if I provide the value to jq select, but the variable doesn't seem to work (or I don't know how to use it).

#!/bin/sh

#this works ***
projectID=$(cat file.json | jq -r '.resource[] | select(.username=="[email protected]") | .id')
echo "$projectID"

[email protected]

#this does not work *** no value is printed
projectID=$(cat file.json | jq -r '.resource[] | select(.username=="$EMAILID") | .id')
echo "$projectID"

推荐答案

还考虑将shell变量(EMAILID)作为jq变量(为便于说明,此处也称为EMAILID)传递:

Consider also passing in the shell variable (EMAILID) as a jq variable (here also EMAILID, for the sake of illustration):

   projectID=$(cat file.json |
     jq -r --arg EMAILID "$EMAILID" '
        .resource[]
        | select(.username==$EMAILID)
        | .id')

后记

出于记录目的,另一种可能性是使用jq的env函数访问环境变量.例如,考虑以下bash命令序列:

Postscript

For the record, another possibility would be to use jq's env function for accessing environment variables. For example, consider this sequence of bash commands:

[email protected]  # not exported
EMAILID="$EMAILID" jq -n 'env.EMAILID'

输出为JSON字符串:

The output is a JSON string:

"[email protected]"

这篇关于将bash变量传递给jq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 22:02