【问题标题】:How to catch "$variable is not defined" in jq?如何在 jq 中捕获“$variable is not defined”?
【发布时间】:2019-11-27 18:32:39
【问题描述】:

让我们假设我正在运行这样的东西:

jq -nr --arg target /tmp \
  '(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"' \
| sh

一切都很好,除非我忘记传递变量$target

$ jq -nr '(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"'
jq: error: $target is not defined at <top-level>, line 1:
(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"
jq: 1 compile error

我怎样才能捕捉到这一点并使用默认值?

我试过了:

  1. $target?
  2. ($target)?
  3. try $target catch null
  4. $target? // null

但这似乎是解析时错误,显然无法在运行时捕获。我错过了任何动态语法吗?

我发现在$ARGS.name中可以找到命令行参数,但是有两个缺点:

  1. 这是在 1.6 版中引入的,但我在 CentOS 7 上有 1.5。
  2. 它不捕获本地定义的变量。

【问题讨论】:

  • 如果没有 $ARGS.name 似乎是不可能的,因为引用未定义的变量是一个编译错误;即它在执行任何代码之前暂停程序
  • 确实,引入 $ARGS 是为了解决(或至少提供一种解决方法)您发现的问题。但是,jq -n '$x'应该返回一个非零错误代码(但它因版本而异)。
  • 至少这会暗示其他人唯一的解决方案就是升级。

标签: jq


【解决方案1】:

假设您需要对 jq 做一些比在文本文件上写“Hello World”更有用的事情。我提出以下建议, 也许我们可以从耶稣那里学到一些编程技巧:

“凯撒的归凯撒,上帝的归神”

假设凯撒是bash shell,上帝是jq,bash适合工作和测试文件、目录和环境变量的存在,jq适合处理json格式的信息。

#!/bin/bash
dest_folder=$1

#if param1 is not given, then the default is /tmp:
if [ -z $dest_folder ]; then dest_folder=/tmp ; fi
echo destination folder:  $dest_folder

#check if destination folder exists
if [ ! -d $dest_folder ]
  then
    echo "_err_ folder not found"
    exit 1
fi

jq -nr --arg target $dest_folder  '(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"' | sh

#if the file is succesfully created, return 0, if not return 1
if [ -e "$dest_folder/sample.txt" ]
  then
    echo "_suc_ file was created ok"
    exit 0
  else
    echo "_err_ when creating file"
    exit 1
fi

现在您可以将此脚本作为一个步骤包含在更复杂的批处理中,因为它与 linux 风格一致,成功时返回 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多