【问题标题】:Bash number comparision error: line 90: [[: 22: syntax error: operand expected (error token is "22")Bash 编号比较错误:第 90 行:[[:22:语法错误:预期操作数(错误标记为“22”)
【发布时间】:2020-07-23 17:23:41
【问题描述】:

假设$commandGetEvents 是一个 json 对象数组。我使用以下命令提取事件 ID,它是一个 1 - 65 的数字,并将其存储在 currentEventId 中。现在让我们假设我有另一个名为 startedEventId 的变量,它包含我正在寻找的值,即 22。

这是 $commandGetEvents 包含的数据示例。

[   
  {
        "eventId": 22,
        "Name" : "Bob"
        "Activity" : "Eat Food"
        "startedEventId" : 15
    },
    {
        "eventId": 21,
        "Name" : "Smith"
        "Activity" : "Ride a bike"
        "startedEventId" : 13
    },
    {
        "eventId": 20,
        "Name" : "Tony"
        "Activity": "Print paper"
        "startedEventId" : 10
    },
]

eventId 是 json 对象的唯一标识符。 & startedEventId 是导致当前事件发生的 json 对象的标识符。

currentEventId=$(jq ".[$index].eventId" <<< ${commandGetEvents})
startedEventid=$(jq ".[${eventCounter}].startedEventId" <<< $commandGetEvents)

当我在 while 循环中回显两个语句时,我得到以下输出。

currentEventId = 1
startedEventId = 22

currentEventId = 2
startedEventId = 22

currentEventId = 3
startedEventId = 22

while 循环一直持续到 currentEventId 的所有元素都用完为止。

我的问题是当我像这样比较两个语句时:

if [[ ${startedId} -eq ${currentEventId} ]] ;
   then
   echo "Equal"
fi

我收到以下错误消息:

line 90: [[: 22: syntax error: operand expected (error token is "22")

【问题讨论】:

  • 什么是startedId
  • 请提供commandGetEvents 的示例值,当与您显示的代码一起使用时,会重现错误;见minimal reproducible example
  • 听起来像是变量中有一些不可打印的错误数据。 printf '%s\n' "${startedId}" "${currentEventId}" | cat -v 的输出是什么?
  • 变量startedId 很可能为空或未设置。
  • -eq 更改为== 可能是一种选择,但也可能隐藏真正的问题。我猜startedIdcurrentEventId 包含"&lt;something&gt; 22" 其中&lt;something&gt; 包含一个运算符..

标签: bash jq


【解决方案1】:
  1. 提供的“JSON”作为 JSON 无效。请修复它。

  2. 在 bash 命令行中使用 jq 时,几乎总是最好将 jq 程序用单引号括起来; bash shell 变量可以使用--arg 或--argjson 传入。例如,考虑以下 sn-p,假设 `commandGetEvents' 是有效的 JSON,遵循 Q 中建议的行:

index=0
currentEventId=$(jq --argjson index $index '.[$index].eventId' <<< ${commandGetEvents})
echo index=$index
echo currentEventId=$currentEventId
  1. 涉及eventCounter 的问题部分有些晦涩,但看起来上面给出的示例可以作为指导。

  2. 比起使用 bash 结构来遍历 JSON 数组,使用 jq 对迭代和选择的支持几乎肯定会更好。例如:

    jq '.[] |选择(.eventId == 22)'

产量:

{
  "eventId": 22,
  "Name": "Bob",
  "Activity": "Eat Food",
  "startedEventId": 15
}

因此,如果您只想要 .eventId == 22 对应的 startedEventId 值(或多个值),您可以这样写:

jq '.[] | select(.eventId == 22) | .startedEventId' <<< ${commandGetEvents}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多