Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json 通过shell脚本从curl结果中提取令牌_Json_Shell_Curl_Token - Fatal编程技术网

Json 通过shell脚本从curl结果中提取令牌

Json 通过shell脚本从curl结果中提取令牌,json,shell,curl,token,Json,Shell,Curl,Token,我写这个剧本 #!/bin/bash # cm.sh curl -i \ -H "Content-Type: application/json" \ -d ' { "auth": { "identity": { "methods": ["password"], "password": { "user": { "name": "admin", "domain": { "id": "default"

我写这个剧本

#!/bin/bash
# cm.sh

  curl -i \
  -H "Content-Type: application/json" \
  -d '
{ "auth": {
    "identity": {
      "methods": ["password"],
      "password": {
        "user": {
          "name": "admin",
          "domain": { "id": "default" },
          "password": "secret"
        }
      }
    }
  }
}' \
  "http://localhost/identity/v3/auth/tokens" ; echo



echo $tokenizer1 
echo $tokenizer2
但它们(awk或sed)都是一样的

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   540  100   312  100   228    312    228  0:00:01 --:--:--  0:00:01  5142
我的目标是将令牌放在一个变量中,以便以后使用。
提前谢谢你们

不使用cURL的直接结果,您可以将结果保存在文件中,并对其使用grep命令。 可能是这样的:

curl -o boulou.txt http://localhost/identity/v3/auth/tokens && cat boulou.txt | grep "X-Subject-Token" | awk '{printf $2}'
编辑,如果您只需要所需的输出,请将
--silent
添加到cURL命令:

curl -o boulou.txt http://localhost/identity/v3/auth/tokens --silent && cat boulou.txt | grep "X-Subject-Token" | awk '{printf $2}'
编辑2:如果要导出并删除文件,可以使用以下方法:

export OS_TOKEN=$(curl -o billy.txt hhttp://localhost/identity/v3/auth/tokens --silent &&  cat billy.txt | grep "X-Subject-Token" | awk '{printf $2}') && rm billy.txt
“当内容存储在变量中时,当我传递JSON文档时,如何使用grep/awk从curl中提取字段中的头?”确实是一个非常棘手且独特的问题

但是,如果您逐渐模仿代码的每一部分来缩小范围,您会发现这是您本可以研究或提出的更简单的问题:

如何在变量的内容上使用grep/awk? 我有一个包含HTTP头的变量,我想提取其中一个头的值。下面是一个例子:

variable='Foo: 1
Bar: 2
Baz: 3'
这就是我试图从
Bar
获取的
2

  # Just hangs
  tokenizer1=$variable `grep "Bar" | awk '{printf $2}'`
  # Is empty
  tokenizer2=$variable | `grep "Bar" | awk '{printf $2}'`
这里的答案是使用
echo
管道传输内容,以便grep可以在stdin上读取:

tokenizer3=$(echo "$variable" | grep "Bar" | awk '{printf $2}')
这很容易应用于您的示例:

tokenizer3=$(echo "$token" | grep "X-Subject-Token" | awk '{printf $2}')
echo "The value is $tokenizer3"

我更新了我的回复@Khalfe telle me,如果你还需要一些东西
awk'/Bar/{print$2}'
——不需要事先的
grep
。我重新打开了它,因为它不是关于解析JSON,而是关于HTTP头