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

如何通过BOTH运行sudo apt-get install来查看安装过程(在我的情况下很长时间) 并将其输出保存到文本文件中?

使用script命令。 它将复制文件中屏幕上的所有内容

 script -c "sudo apt-get install things" script-file.script 

您可以使用tee命令来完成此任务。

 sudo apt-get install someapp 2>&1 | tee ~/someappInstall.txt 

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

注意:正如其他人所提到的, 2>&1是将STDERR重定向到STDOUT以捕获任何错误所必需的。 有关2>&1实际执行的操作的详细说明,请参阅此StackOverflow问题 。

tee将按要求完成工作。

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

 sudo apt-get install your_software | tee log_file.txt 

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

 sudo apt-get install your_software 2>&1 | tee log_file.txt 

apt-get(和APT一般)的优点之一是它们几乎可以存储日志文件,甚至是/var/log/apt运行的任何命令的终端输出。 例如,这是我的/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 

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

 ➜ ~ 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) ... 

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

尝试tee命令。 你可以在这里找到一些例子。

简单用法:

   | tee file 

例:

  sudo apt-get install whatYouWant | tee outputFile