【问题标题】:syntax error: operand expected (error token is "<")语法错误:预期操作数(错误标记为“<”)
【发布时间】:2019-08-12 15:41:28
【问题描述】:

当我运行这段代码时,我得到 ./file.sh: line 23: ((: j<: syntax error: operand expected token is thise repos json>

Json 文件数据如下图所示 enter image description here

#!/bin/bash
IFS=$IFS,
usr='*************'
pwd='*************'
url='*************'
curl --header "Content-Type: application/json" --request GET 
"https://$usr:$pwd@$url" |grep login|cut -d ':' -f2|sed 's/,//g'|sed 
's/"//g' >> MHEOrgs.txt
File=./MHEOrgs.txt

while read orgs; do

#orgs= $i
curl -s --header "Content-Type: application/json" --request GET --user 
"$usr:$pwd" $url/$orgs/repos?page=[1-100] >> $orgs+Repos.json
jq -r '.[].name' $orgs+Repos.json >>$orgs+Repolist.json
user="https://$usr:$pwd@********/$orgs/"
repos=`cat $orgs+Repolist.json`
for i in $repos;
do
    echo $user"$i".git
    #Below commabd will perform scan operation on the githubrepos and 
    generates multiple json files
    ~/go/bin/gitleaks --repo=$user"$i" --report=$orgs+$i.json
     #Now i wanted to get below values from each file generated above.
     numsecs=$(jq ".|length" $orgs+$i.json)
     for ((j=0;j<$numsecs;j++))
     do
        commit=$(jq -r ".[$j]|.commit" $orgs+$i.json)
        author=$(jq -r ".[$j]|.author" $orgs+$i.json)
        file=$(jq -r ".[$j]|.file" $orgs+$i.json)
        repo=$(jq -r ".[$j]|.repo" $orgs+$i.json)
        if [ "${commit}" != "null" ]; then

        echo "\"$repo\"," "\"$file\"," "\"$author\"," "\"$commit\",">> 
        gitleaks-scan-results.csv
        else
        echo "No leaks found"
        fi


      done


    done

done < $File

【问题讨论】:

  • 一个好的minimal reproducible example 最小:它只有最短的代码来重现给定的错误。
  • 我还强烈建议养成通过shellcheck.net 运行代码并在此处提问之前修复它发现的所有内容的习惯;这样我们就不需要挑选潜在的报价问题 &c。并找出哪些与给定问题相关,哪些实际上不相关。
  • ...顺便说一句,我建议bash -x yourscript 在运行时记录每一行;这样您就可以看到实际正在运行什么命令来填充numsecs,然后自己手动重新运行以进行调试。
  • 我还强烈建议尝试减少jq 调用的数量。没有充分的理由为每个作者运行一次jq,每次提交一次,等等;您可以运行 jq 一次,并让它以您需要的确切格式提取所有内容。
  • ...例如:jq -r '.[] | [.repo, .file, .author, .commit] | @csv'

标签: bash for-loop jq


【解决方案1】:

如果 numsecs 实际上未设置为(单个整数)数字,则会发生这种情况。

可能发生的一种情况是,如果您的 JSON 文件中根本没有任何记录;或者如果它有多个(这意味着jq 的输出中有多个数字,bash 无法正确解析为单个数字)。


一些例子

零对象文档案例:

$ numsecs=$(jq '. | length' <<<'')
$ declare -p numsecs
declare -- numsecs=""
$ for ((j=0;j<$numsecs;j++)); do break; done
-bash: ((: j<: syntax error: operand expected (error token is "<")

多对象文档案例:

$ numsecs=$(jq '. | length' <<<$'[1,2]\n[3,4]')
$ declare -p numsecs
declare -- numsecs="2
2"
$ for ((j=0;j<$numsecs;j++)); do break; done
-bash: ((: j<2
2: syntax error in expression (error token is "2")

【讨论】:

  • 当我执行我的脚本时,我得到这个 jq 错误,当它没有找到它正在寻找的 json 文件时。如果没有数据,脚本不会创建文件。但是我的 jq 语句将搜索所有文件并提取数据。所以,当它找不到文件时,就是我收到错误的时候。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多