解析来自curl + awk的奇怪行为 [英] Strange behavior when parsing result from curl + awk

查看:190
本文介绍了解析来自curl + awk的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ubuntu上使用curl,我试图获取受以下方面启发的Jenkins版本:

Using curl on ubuntu I am trying to fetch the Jenkins version inspired by:

https://wiki.jenkins.io/display/JENKINS/Remote + access + API

在bash脚本中,我这样做:

In a bash script I do:

VERSION=$(curl -k -i -X GET --insecure --silent --header \"Authorization: Bearer $TOKEN \" $URL | grep -Fi X-Jenkins: | awk '{print $2}')
echo "__A__[${VERSION}]__B__"

但是当我运行脚本时,我得到了:

But when I run the script I get:

]__B__2.89.2

因此由于某些原因,前缀:__A__[被吞下,并且后缀被转换为前缀.

So for some reason the prefix: __A__[ gets swallowed and the suffix gets turned into a prefix.

我还尝试使用以下方法修剪输出:

I have also tried to trim the output with:

VERSION=$(curl -k -i -X GET --insecure --silent --header \"Authorization: Bearer $TOKEN \" $URL | grep -Fi X-Jenkins: | awk '{print $2}' | sed -e 's/^[ \t]*//')

但是它给出了相同的结果.

But it gives the same result.

如下所示,我也尝试过:

As suggested below I have also tried with:

echo '__A__['"${VERSION}"']__B__'

但是仍然给出相同/错误的结果.

But still gives the same/wrong result.

我尝试过的其他一些事情(给出了相同的结果)

A few other things I have tried (giving the same result)

输出相同/错误

VERSION=$(curl -k -i -X GET --insecure --silent --header \"Authorization: Bearer $TOKEN \" $URL | grep -i X-Jenkins: | awk '{print $2}')
echo '__A__['"${VERSION}"']__B__'

输出相同/错误

VERSION=$(curl -k -i -X GET --insecure --silent --header \"Authorization: Bearer $TOKEN \" $URL | grep X-Jenkins: | awk '{print $2}')
echo '__A__['"${VERSION}"']__B__'

基于以下建议,我现在尝试:

Based on below suggestion I have now tried:

echo $VERSION|od -ax

哪个给:

0000000   2   .   8   9   .   2  cr  nl
           2e32    3938    322e    0a0d
0000010

如果我将其与:

VERSION_TEMP="2.89.2"
echo $VERSION_TEMP|od -ax

我得到:

0000000   2   .   8   9   .   2  nl
           2e32    3938    322e    000a
0000007

因此,看起来是引起问题的VERSION变量中的cr(不确定如何如上所述解释前缀/后缀的整个反转).

So looks like its the cr in the VERSION var that is causing the issue (not sure how that explains the whole reversing of prefix/suffix as described above).

已解决:根据罗密欧的输入,我现在可以使用它添加|tr -d '\r'了:

SOLVED: Based on input from Romeo I now got it to work with adding |tr -d '\r' :

VERSION=$(curl -k -i -X GET --insecure --silent --header \"Authorization: Bearer $TOKEN \" $URL | grep X-Jenkins: | awk '{print $2}'|tr -d '\r')

推荐答案

显然,输出包含DOS回车.

Apparently the output contains a DOS carriage return.

尝试添加tr -d '\015':

version=$(curl -k -i -X GET --insecure --silent --header \"Authorization: Bearer $TOKEN \" "$URL" |
    tr -d '\015' |
   awk 'tolower($0) !~ /x-jenkins:/{print $2}')
echo "__A__[$version]__B__"

大写变量名保留供系统使用,因此我也将小写变量名更改为小写,并删除了没用的grep.

Uppercase variable names are reserved for system use, so I changed yours to lower case, too, and removed the useless grep.

这篇关于解析来自curl + awk的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆