如何在控制台上显示命令行的输出并将输出保存到文本文件中?

25 command-line apt

我怎么可以运行sudo apt-get install通过BOTH看到安装的过程中(长在我的情况)其输出保存到一个文本文件?

Aar*_*ron 52

您可以使用该tee命令来完成此操作。

sudo apt-get install someapp 2>&1 | tee ~/someappInstall.txt
Run Code Online (Sandbox Code Playgroud)

在这里查看更多信息,或执行man tee

注意:正如其他人提到的,2>&1有必要将 STDERR 重定向到 STDOUT 以捕获任何错误。请参阅此 StackOverflow 问题以获得对2>&1实际作用的良好解释。

  • 这比 `script` 更实用,因为命令不必被引用。所以像 bash 补全这样的优势更容易实现。 (2认同)
  • @Dan:脚本不需要`-c "something ..."`: if 将把你放到一个 shell 中,并在你退出该 shell 时完成。允许多个命令等。此外,它还保留更多“格式化”信息,允许重播更多内容(例如:清除屏幕等)(但这也会弄乱输出...... ymmv) (2认同)
  • @Dan + 使用函数、别名、内置函数,甚至命令组和子 shell。这应该是 IMO 接受的答案。 (2认同)

exo*_*ore 17

使用script命令。它将复制所有进入屏幕的文件

script -c "sudo apt-get install things" script-file.script
Run Code Online (Sandbox Code Playgroud)

  • @BryceAtNetwork23 `history` 是内置的 shell,而不是外部命令。发生的情况是:1)脚本启动,2)脚本搜索历史命令,没有找到它,所以它猜测它应该通过shell运行它。3) 脚本通过 shell** 运行命令 `history` ** 4) 一个新的 shell 启动并执行 history 内部命令。由于这是一个新的非交互式shell,历史无话可说。 (10认同)
  • @BryceAtNetwork23。你试过命令吗?脚本**确实**将输出发送到屏幕。 (2认同)

小智 15

tee 将按要求完成工作。

要将输出捕获到文件中,请使用:

sudo apt-get install your_software | tee log_file.txt
Run Code Online (Sandbox Code Playgroud)

这只会捕获输出,而不会捕获任何错误消息。如果你还想记录错误信息,修改命令为:

sudo apt-get install your_software 2>&1  | tee log_file.txt
Run Code Online (Sandbox Code Playgroud)


Bra*_*iam 9

apt-get(以及一般的 APT)的优点之一是它们将几乎所有内容的日志文件存储在/var/log/apt. 例如,这是 my 中的最后一个条目/var/log/apt/term.log

Log started: 2014-06-20  16:46:08
(Reading database ... 252472 files and directories currently installed.)
Removing xdotool (1:3.20130111.1-3.1) ...
Processing triggers for man-db (2.6.7.1-1) ...
Log ended: 2014-06-20  16:46:33
Run Code Online (Sandbox Code Playgroud)

现在,与实际输出进行比较:

?  ~  sudo apt-get remove xdotool 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following package was automatically installed and is no longer required:
  libxdo3
Use 'apt-get autoremove' to remove it.
The following packages will be REMOVED:
  xdotool
0 upgraded, 0 newly installed, 1 to remove and 2 not upgraded.
After this operation, 135 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 252472 files and directories currently installed.)
Removing xdotool (1:3.20130111.1-3.1) ...
Processing triggers for man-db (2.6.7.1-1) ...
Run Code Online (Sandbox Code Playgroud)

它为我节省了几行在大多数情况下不相关的行,并且它会自动执行。所以,你不需要任何额外的命令来做你想做的事,apt-get 会为你做。