首页 文章

在卷曲响应主体的末尾自动添加换行符

提问于
浏览
170

如果curl请求的HTTP响应主体不包含尾随换行符,我最终会遇到这个非常烦人的情况,其中shell提示符位于行的中间,并且当我放入最后一个卷曲时,转义被搞砸了 . 屏幕上的命令,删除该curl命令中的字符删除错误的字符 .

例如:

[root@localhost ~]# curl jsonip.com
{"ip":"10.10.10.10","about":"/about"}[root@localhost ~]#

有没有一个技巧可以用来在卷曲响应结束时自动添加换行符,以便在屏幕左边缘提示回来?

3 回答

  • 313

    从man文件:

    为了更好地让脚本程序员了解curl的进度,引入了-w / - write-out选项 . 使用此选项,您可以指定要从中提取的先前传输中的哪些信息 . 要显示与一些文本和结束换行符一起下载的字节数量:curl -w'我们下载了%字节\ n'www.download.com

    因此,请尝试将以下内容添加到 ~/.curlrc 文件中:

    -w "\n"
    
  • 80

    试试看:

    curl jsonip.com; echo
    

    OUTPUT

    {"ip":"x.x.x.x","about":"/about"}
    

    就这么简单;)

    (并且不限于curl命令,但所有未使用换行符完成的命令)

  • 7

    有关更多信息以及卷曲后的干净新线

    ~/.curlrc

    -w "\nstatus=%{http_code} %{redirect_url} size=%{size_download} time=%{time_total} content-type=\"%{content_type}\"\n"
    

    (有更多选项可供选择here

    如果请求未被重定向,或者您使用 -L 来跟踪重定向,则 redirect_url 将为空 .

    示例输出:

    ~ ➤  curl https://www.google.com
    <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
    <TITLE>302 Moved</TITLE></HEAD><BODY>
    <H1>302 Moved</H1>
    The document has moved
    <A HREF="https://www.google.co.uk/?gfe_rd=cr&amp;ei=FW">here</A>.
    </BODY></HTML>
    
    status=302 https://www.google.co.uk/?gfe_rd=cr&ei=FW size=262 time=0.044209 content-type="text/html; charset=UTF-8"
    ~ ➤
    

    Edit ,为了使事物更具可读性,可以将ANSI颜色添加到 -w 行,直接编写并不容易,但this脚本可以生成带颜色的 ~/.curlrc 文件 .

    #!/usr/bin/env python3
    from pathlib import Path
    import click
    chunks = [
        ('status=', 'blue'),
        ('%{http_code} ', 'green'),
        ('%{redirect_url} ', 'green'),
        ('size=', 'blue'),
        ('%{size_download} ', 'green'),
        ('time=', 'blue'),
        ('%{time_total} ', 'green'),
        ('content-type=', 'blue'),
        ('\\"%{content_type}\\"', 'green'),
    ]
    content = '-w "\\n'
    for chunk, colour in chunks:
        content += click.style(chunk, fg=colour)
    content += '\\n"\n'
    
    path = (Path.home() / '.curlrc').resolve()
    print('writing:\n{}to: {}'.format(content, path))
    path.write_text(content)
    

相关问题