如何提取最近的终端命令的输出? [英] How to pull the output of the most recent terminal command?
问题描述
我正在构建一个CLI,该CLI在运行时需要最新执行的bash命令的输出。
I'm building a CLI that, when run, requires the output of the most recently executed bash command. Is it possible to pull this output without recomputing the command?
例如,假设我运行 python main.py
并收到此错误:
For example, let's say I run python main.py
and receive this error:
File "main.py", line 41
messages_list.insert(0, { "author" : "dummy_author0", "message" : " " } )
^
IndentationError: unindent does not match any outer indentation level
然后我想运行一个命令,该命令会自动提取此错误消息并对其执行某些操作,而无需重新运行 python main.py
。
I'd like to then run a command that automatically pulls this error message and does something with it, without re-running python main.py
.
我想运行 command1; command2
可以为 command2
提供一种方法,因为执行以下命令后可以提取 command1
的输出两者都可能被视为一个进程,但是我不确定如何处理。
I'm thinking that running command1; command2
could provide a way for command2
to pull the output of command1
since the execution of both in sequence might be treated as a single process, but I'm not sure how.
推荐答案
外壳(和终端)
我会将命令包装在shell脚本中,该脚本调用脚本
命令,例如
I'd wrap the command in a shell-script which calls the script
command, e.g.,
- 创建一个临时文件名(取决于系统,但例如使用
mktemp
), - 使用该临时文件作为
脚本
的输出,而不是默认的打字稿
。 在命令中将 - 传递给
script
,回显退出代码,因为脚本
将在shell脚本中向您隐藏 - ,过滤回车符等,例如,其中
script2log
和 - 最后一个过滤后的输出中有一个具有退出代码。使用它作为shell脚本的退出代码
- create a temporary filename (system-dependent, but for example with
mktemp
), - use that temporary file as the output for
script
, rather than the defaulttypescript
. - in the command passed to
script
, echo the exit-code sincescript
will hide that from you - in the shell-script, filter out carriage-returns, etc., e.g., with
script2log
, and - the last line of the filtered output would have the exit-code. Use that for the exit-code of the shell-script
对于您的CLI程序,使shell脚本接受一个参数,该参数可以告诉shell脚本在哪里写命令的输出。可能是另一个临时文件,避免了将命令输出重定向到文件或管道的问题,从而使输出不再是终端。
For your CLI program, make the shell-script accept a parameter which tells the shell-script where to write the output of the command. Likely that is another temporary file, avoiding the problem of redirecting the output of the command to a file or pipe, making the output no longer a terminal.
使用 script
的Linux变体,可能是这样的:
If you're using the Linux variant of script
, it could be something like this:
#!/bin/sh
# $1 = command
# $2 = output
code=0
tempfile=$(mktemp)
trap "rm -f \$tempfile; exit \$code" EXIT INT QUIT HUP
script -q -c "$1; echo \$?" $tempfile
script2log <$tempfile >$2
code=$(tail -n 1 $tempfile)
这篇关于如何提取最近的终端命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!