如何在同一个文本文件中输出linux命令和返回结果?

Ric*_*d77 3 command-line

到目前为止,我看到的所有命令都类似于command > fileor command >> file,它将结果输出到指定的文件。例如,当我输入 时openssl version > lab4.txt,我在文本文件中看到的只有OpenSSL 1.0.1e-fips 11 Feb 2013.

如果我想输出我输入的命令和返回的结果,像这样一个在另一个下面怎么办?

linux2[20]% openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助

hee*_*ayl 6

重定向操作符command > file将重定向命令的 STDOUT 或命令的 STDERR(command 2> file如果像&>在 bash 或任何 shell 中通过可移植command > file 2>&1方式使用)或两者都使用。我不知道使用重定向的任何直接方法可以实现您的需要。

虽然可以使用该script程序。它基本上会保存该script会话中终端上打印的所有内容。

来自man script

script makes a typescript of everything printed on your terminal. 
It is useful for students who need a hardcopy record of an 
interactive session as proof of an assignment, as the typescript file 
can be printed out later with lpr(1).
Run Code Online (Sandbox Code Playgroud)

script只需script在终端中键入即可启动会话,所有后续命令及其输出都将保存在typescript当前目录中命名的文件中。您也可以通过以下方式将结果保存到不同的文件script

script output.txt
Run Code Online (Sandbox Code Playgroud)

要注销screen会话(停止保存内容),只需键入exit.

下面是一个例子:

script makes a typescript of everything printed on your terminal. 
It is useful for students who need a hardcopy record of an 
interactive session as proof of an assignment, as the typescript file 
can be printed out later with lpr(1).
Run Code Online (Sandbox Code Playgroud)

现在,如果我阅读文件:

script output.txt
Run Code Online (Sandbox Code Playgroud)

script也有许多选项,例如安静运行-q( --quiet) 而不显示/保存程序消息,它还可以运行特定命令-c( --command) 而不是会话,它还具有许多其他选项。检查man script以获得更多想法。