@@ -229,7 +229,7 @@ sections:
229
229
* `-f filename` / `--from-file filename`:
230
230
231
231
Read filter from the file rather than from a command line, like
232
- awk's -f option. You can also use '#' to make comments.
232
+ awk's -f option.
233
233
234
234
* `-L directory`:
235
235
@@ -3537,6 +3537,68 @@ sections:
3537
3537
(.posts[] | select(.author == "stedolan") | .comments) |=
3538
3538
. + ["terrible."]
3539
3539
3540
+ - title : Comments
3541
+
3542
+ body : |
3543
+
3544
+ You can write comments in your jq filters using `#`.
3545
+
3546
+ A `#` character (not part of a string) starts a comment.
3547
+ All characters from `#` to the end of the line are ignored.
3548
+
3549
+ If the end of the line is preceded by an odd number of backslash
3550
+ characters, the following line is also considered part of the
3551
+ comment and is ignored.
3552
+
3553
+ For example, the following code outputs `[1,3,4,7]`
3554
+
3555
+ [
3556
+ 1,
3557
+ # foo \
3558
+ 2,
3559
+ # bar \\
3560
+ 3,
3561
+ 4, # baz \\\
3562
+ 5, \
3563
+ 6,
3564
+ 7
3565
+ # comment \
3566
+ comment \
3567
+ comment
3568
+ ]
3569
+
3570
+ Backslash continuing the comment on the next line can be useful
3571
+ when writing the "shebang" for a jq script:
3572
+
3573
+ #!/bin/sh --
3574
+ # sum - Output the sum of the given arguments (or stdin)
3575
+ # usage: sum [numbers...]
3576
+ # \
3577
+ exec jq --args -MRnf "$0" -- "$@"
3578
+
3579
+ $ARGS.positional |
3580
+ reduce (
3581
+ if . == []
3582
+ then inputs
3583
+ else .[]
3584
+ end |
3585
+ . as $dot |
3586
+ try tonumber catch false |
3587
+ if not or isnan then
3588
+ @json "sum: Invalid number \($dot).\n" | halt_error(1)
3589
+ end
3590
+ ) as $n (0; . + $n)
3591
+
3592
+ The `exec` line is considered a comment by jq, so it is ignored.
3593
+ But it is not ignored by `sh`, since in `sh` a backslash at the
3594
+ end of the line does not continue the comment.
3595
+ With this trick, when the script is invoked as `sum 1 2`,
3596
+ `/bin/sh -- /path/to/sum 1 2` will be run, and `sh` will then
3597
+ run `exec jq --args -MRnf /path/to/sum -- 1 2` replacing itself
3598
+ with a `jq` interpreter invoked with the specified options (`-M`,
3599
+ `-R`, `-n`, `--args`), that evaluates the current file (`$0`),
3600
+ with the arguments (`$@`) that were passed to `sh`.
3601
+
3540
3602
- title : Modules
3541
3603
body : |
3542
3604
0 commit comments