Do jq's variable bindings work through functions?

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Do jq's variable bindings work through functions?



I have the following script for jq:


$ jq -n 'def f: $a; 1 as $a | $a'
1



Since f is not used, this outputs 1 as expected. However:


f


1


$ jq -n 'def f: $a; 1 as $a | f'
jq: error: a/0 is not defined at <top-level>, line 1:
def f: $a; 1 as $a | f
jq: 1 compile error



Is it not possible to use variable bindings through functions?




1 Answer
1



In jq, the scoping of variables is defined lexically. With f defined as $a, f can only be evaluated as $a if $a is "visible" to f. This can be achieved, for example, using one of the command-line options such as —arg or —argjson.


f


$a


f


$a


$a


f



It can also be achieved as illustrated by:


jq -n '2 as $a | def f: $a; f'



Note also that lexical scoping works with sub-functions as well:


def f($a): def g: $a; g;
f(1)



yields:


1






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

LMA Q,dXIMNNA,vx6C4DSqP v BoZ
ir,18bRGukkD2Qe Ia3,GGM PTJhRL

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results