2017-03-16 131 views
1

如何將Linux命令的輸出與命令一起重定向到文件?命令重定向

ls -l >> test.txt一樣只會將輸出而不是命令也重定向到文件。我是新手

+1

也許你正在尋找['script'](http://man7.org/linux/man-pages/man1/script.1.html)命令。 –

回答

1

使用script命令就可以登錄,這將節省整個終端會話,直到你exit程序,例如

命令執行

[email protected]:/tmp$ script test.log 
Script started, file is test.log 
[email protected]:/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  

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

這是記錄:

[email protected]:/tmp$ cat test.log 
Script started on Thursday 16 March 2017 11:43:06 PM IST 
[email protected]:/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  

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

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

如果你不想使用script工具有一些替代品,使用設置-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="[email protected]"; echo $a >log ; "[email protected]" >>log 2>&1;cat log;return; } 
$ logme pwd 
pwd 
/home/gv/Desktop/PythonTests 

PS :您可以offcourse輸出發送到另一個文件,即logme PWD >>一般日誌

最後,你可以建立像波紋管自定義腳本,也使得集-v使用(詳細):

exec 3>&2 2>log 4<log 
set -vx 
"[email protected]" >&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.