天天看點

Linux中記錄終端輸出到文本檔案

Linux中記錄終端輸出到文本檔案

一,如何把指令運作的結果儲存到檔案當中?

這個問題太簡單了,大家都知道,用 > 把輸出轉向就可以了

  

例子:

 $ ls > ls.txt    #或者 ls-->ls.txt    #把ls指令的運作結果儲存到檔案ls.txt中

  [lhd@hongdi ~]$ ls > ls.txt

  [lhd@hongdi ~]$ cat ls.txt

  1.gtkrc-2.0

  2009

  a

  amsn_received

  a.tar.gz

說明:

是把輸出轉向到指定的檔案,如檔案已存在的話也會重新寫入,檔案原内容不會保留

 >> 是把輸出附向到檔案的後面,檔案原内容會保留下來

二,如何能在輸出資訊的同時把資訊記錄到檔案中?

  我們在上面的例子中可以看到,我們使用輸出轉向,指令在終端上的輸出轉向到了檔案中,但如果我希望能同時在終端上看到輸出資訊怎麼辦?

  我們可以使用這個指令: tee

  解釋一下tee的作用:

read from standard input and write to standard output and files

它從标準輸入讀取内容并将其寫到标準輸出和檔案中

看例子:

[lhd@hongdi ~]$ ls | tee ls_tee.txt

1.gtkrc-2.0

2009

a

amsn_received

a.tar.gz

[lhd@hongdi ~]$ cat ls_tee.txt

備注:

使用 tee時,如果想保留目标檔案原有的内容怎麼辦?可以使用 -a參數

  -a, --append

  append to the given FILEs, do not overwrite

附加至給出的檔案,而不是覆寫它

三,多個指令的輸出都需要記錄,可以用script

  script這個指令很強大,可以記錄終端的所有輸出到相應的檔案中

  看例子:

[lhd@hongdi ~]$ script

Script. started, file is typescript

[lhd@hongdi ~]$ ls

1.gtkrc-2.0 c.tar kmess-2.0alpha2.tar.gz secpanel-0.5.3-1.noarch.rpm

2009 DownZipAction.php kmesslog secpanel-0.5.4-2.noarch.rpm

[lhd@hongdi ~]$ exit

exit

Script. done, file is typescript

[lhd@hongdi ~]$ cat typescript

Script. started on 2009年02月08日 星期日 18時56分52秒

Script. done on 2009年02月08日 星期日 18時57分00秒

1,我們在啟動script時沒有指定檔案名,它會自動記錄到目前目錄下一個名為 typescript的檔案中。也可以用 -a參數 指定檔案名

[lhd@hongdi ~]$ script. -a example.txt

Script. started, file is example.txt

此時終端的輸出内容被記錄到 example.txt這個檔案中

2,退出script時,用exit

感到奇怪嗎?事實上script就是啟動了一個shell,看一下ps auxfww 的資訊就知道了

lhd 17738 0.1 3.2 152028 33328 ? Sl 18:30 0:03 /usr/bin/konsole

lhd 17740 0.0 0.1 6372 1720 pts/1 Ss 18:30 0:00 _ /bin/bash

lhd 17900 0.0 0.0 5344 628 pts/1 S 19:01 0:00 | _ script

lhd 17901 0.0 0.0 5348 464 pts/1 S 19:01 0:00 | _ script

lhd 17902 0.5 0.1 6372 1688 pts/2 Ss 19:01 0:00 | _ bash -i

3,檢視typescript的内容,可以看到它同時記錄下了script的啟動和結束時間

作者:琦彥

來源:CSDN

原文:

https://blog.csdn.net/fly910905/article/details/90377035

版權聲明:本文為部落客原創文章,轉載請附上博文連結!