命令重定向

时间:2017-03-16 18:03:46

标签: linux bash

如何将Linux命令的输出与命令一起重定向到文件?

ls -l >> test.txt类似,只会将输出重定向,而不是将命令重定向到文件。我是新手

2 个答案:

答案 0 :(得分:1)

使用script命令,您可以记录,这将保存整个终端会话,直到您exit该程序为止,例如

执行的命令

akshay@db-3325:/tmp$ script test.log
Script started, file is test.log
akshay@db-3325:/tmp$ cal
     March 2017       
Su Mo Tu We Th Fr Sa  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31     

akshay@db-3325:/tmp$ uptime
 23:43:16 up  4:31,  1 user,  load average: 0.78, 0.67, 0.44
akshay@db-3325:/tmp$ w
 23:43:18 up  4:31,  1 user,  load average: 0.72, 0.66, 0.43
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
akshay   tty7     :0               19:12    4:31m  7:49   0.28s /sbin/upstart --user
akshay@db-3325:/tmp$ whoami
akshay
akshay@db-3325:/tmp$ echo 'something'
something
akshay@db-3325:/tmp$ exit
exit
Script done, file is test.log

这是记录的内容:

akshay@db-3325:/tmp$ cat test.log 
Script started on Thursday 16 March 2017 11:43:06 PM IST
akshay@db-3325:/tmp$ cal
     March 2017       
Su Mo Tu We Th Fr Sa  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31     

akshay@db-3325:/tmp$ uptime
 23:43:16 up  4:31,  1 user,  load average: 0.78, 0.67, 0.44
akshay@db-3325:/tmp$ w
 23:43:18 up  4:31,  1 user,  load average: 0.72, 0.66, 0.43
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
akshay   tty7     :0               19:12    4:31m  7:49   0.28s /sbin/upstart --user
akshay@db-3325:/tmp$ whoami
akshay
akshay@db-3325:/tmp$ echo 'something'
something
akshay@db-3325:/tmp$ exit
exit

Script done on Thursday 16 March 2017 11:43:38 PM IST

答案 1 :(得分:0)

如果您不想使用script实用程序,可以使用set -x bash功能:

$ exec 2>log; set -x; pwd >&2;set +x;exec 2>&1;cat log
+ pwd
/home/gv/Desktop/PythonTests
+ set +x

或者您也可以使用自定义函数而不会出现棘手的重定向:

$ function logme { a="$@"; echo $a >log ; "$@" >>log 2>&1;cat log;return; }
$ logme pwd  
pwd
/home/gv/Desktop/PythonTests

PS:您可以将输出发送到另一个文件,即logme pwd>>一般日志

最后,你可以像bellow一样构建一个自定义脚本,也可以使用set -v(verbose):

exec 3>&2 2>log 4<log 
set -vx
"$@" >&2
set +vx 
cat <&4 >&1  # Optionally combine with |tail -n +2 |head -n -2 
#The cat is used to display in command line what is logged inside the file.