如果curl请求的HTTP响应体不包含末尾换行符,那么我最终会遇到这种非常恼人的情况,即shell提示符位于行中间,转义非常混乱,以至于当我在屏幕上放置最后一个curl命令时,从该curl命令中删除字符会删除错误的字符。

例如:

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

是否有一种技巧可以用来在curl响应的末尾自动添加换行符,以使提示符回到屏幕的左边缘?


用这个:

curl jsonip.com; echo 

如果你需要对管道进行分组:

{ curl jsonip.com; echo; } | tee new_file_with_newline

输出

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

就是这么简单;)

(并且不局限于curl命令,而是所有不以换行符结束的命令)

从男子档案中可以看出:

为了更好地让脚本程序员了解进度 Curl, -w/——write-out选项被引入。使用它,您可以指定 您想从以前的传输中提取哪些信息。 来显示下载的字节数以及一些文本和 换行符结束: curl -w `我们下载了%{size_download} bytes\n ` www.download.com

因此,尝试在~/中添加以下内容。curlrc文件:

-w "\n"

更多信息以及一个干净的新行后卷曲

~ / . curlrc

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

(更多选项请点击此处)

redirect_url将为空白,如果请求没有被重定向或您使用-L跟随重定向。

示例输出:

~ ➤  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"
~ ➤  

编辑,为了使内容更具可读性,你可以在-w行中添加ANSI颜色,这并不容易直接编写,但这个脚本可以生成~/。带有颜色的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)

bash的一般解决方案是在命令提示符中添加换行符:

参见相关问题(如何在bash提示符前有换行符? )及相应答案

这个解决方案涵盖了每个命令,而不仅仅是curl。

echo $PS1 # To get your current PS1 env variable's value aka '_current_PS1_'
PS1='\n_current_PS1_'

唯一的副作用是在每个第二行之后都有命令提示符。

当命令输出结束时没有新行时,我设法获得动态添加到提示符的新行。因此,它不仅适用于curl,而且适用于任何其他命令。

# https://github.com/dylanaraps/pure-bash-bible#get-the-current-cursor-position
new_line_ps1() {
  local _ y x _
  local LIGHT_YELLOW="\001\033[1;93m\002"
  local     RESET="\001\e[0m\002"

  IFS='[;' read -p $'\e[6n' -d R -rs _ y x _
  if [[ "$x" != 1 ]]; then
    printf "\n${LIGHT_YELLOW}^^ no newline at end of output ^^\n${RESET}"
  fi
}

PS1="\$(new_line_ps1)$PS1"

我的答案在UL网站:https://unix.stackexchange.com/a/647881/14907