資料流重導向

  1. 指令執行過程之資料傳輸

    \begin{picture}(380,120)
\setlength{\unitlength}{1mm}
......
  2. 執行 cat /etc/crontab /etc/dywang,standard input 與 standard output 同時出現。
    [dywang@dywHome ~]$ cat /etc/crontab /etc/dywang
    # /etc/crontab 存在,螢幕出現以下 standard output
    SHELL=/bin/bash
    
    MAILTO=root
    HOME=/
    
    # run-parts
    01 * * * * root nice -n 19 run-parts --report /etc/cron.hourly
    02 4 * * * root nice -n 19 run-parts --report /etc/cron.daily
    22 4 * * 0 root nice -n 19 run-parts --report /etc/cron.weekly
    42 4 1 * * root nice -n 19 run-parts --report /etc/cron.monthly
    # /etc/dywang 不存在,螢幕出現以下 standard error
    cat: /etc/dywang: No such file or directory
    
  3. 傳送指令
    1. 標準輸入(stdin) :代碼為 0 ,使用 < 或 <<
    2. 標準輸出(stdout):代碼為 1 ,使用 > 或 >>
    3. 標準錯誤輸出(stderr):代碼為 2 ,使用 2> 或 2>>
      >, 1>   標準輸出至檔案,該檔案被覆蓋或建立。
      >>, 1>>   標準輸出至檔案,該檔案被建立或累加。
    command 2> 裝置或檔案 錯誤輸出至檔案,該檔案被覆蓋或建立。
      2>>   錯誤輸出至檔案,該檔案被建立或累加。
      <   輸入
      <<   結束的輸入字元
  4. 檔案的建立方式
    [root@linux ~]# ls -l /  >  ~/rootfile
    # 將 ls -l / 要列出到螢幕上的資料『重新導向』到 ~/rootfile 檔案。
    
    1. 該檔案( 本例中是 ~/rootfile )若不存在,系統會自動建立;
    2. 檔案存在時,系統會先將檔案內容清空再將資料寫入;
    3. > 輸出到一個既存檔案中,該檔案會被覆蓋。
  5. 下達 >>>
    # 將目前目錄下的檔案資訊儲存到 list.txt
    [root@linux ~]# ls -al > list.txt
    
    # 將根目錄下的資料累加到 list.txt
    [root@linux ~]# ls -al / >> list.txt
    
  6. 下達 2>
    [csie@linux ~]$ find /home -name testing
    find: /home/test1: Permission denied   %*<== Starndard error*)
    find: /home/root: Permission denied    %*<== Starndard error*)
    find: /home/masda: Permission denied   %*<== Starndard error*)
    /home/csie/testing                   %*<== Starndard output*)
    
    [csie@linux ~]$ find /home -name testing > list_right 2> list_error
    [csie@linux ~]$ find /home -name testing > list_right 2> /dev/null
    
  7. 下達 2>&1:標準輸出與標準錯誤輸出同時寫入同一個檔案
    [csie@linux ~]$ find /home -name testing > list 2> list  %*<==錯誤寫法*)
    ## 習題:請問上面命令的執行結果為何?
    [csie@linux ~]$ find /home -name testing > list 2>&1     %*<==正確寫法*)
    
  8. 使用 grep 命令過濾檔案 /usr/share/doc/autofs-5.0.7/README 中包含 configure 字串的所有行,共有 3 行。
    [root@kvm7 ~]# grep configure /usr/share/doc/autofs-5.0.7/README
    	./configure
    to configure the system.  See README.options for options that you can
    give configure.
    
  9. grep 命令過濾檔案 /usr/share/doc/autofs-5.0.7/README 中包含 configure 字串的 3 行原先顥示在螢幕上,現導向到檔案 /root/autofs.txt。
    [root@kvm7 ~]# grep configure /usr/share/doc/autofs-5.0.7/README > /root/autofs.txt
    
  10. 查看檔案 /root/autofs.txt 內容,與 grep 命令過濾檔案 /usr/share/doc/autofs-5.0.7/README 中包含 configure 字串的 3 行完全一樣。
    [root@kvm7 ~]# cat /root/autofs.txt
    	./configure
    to configure the system.  See README.options for options that you can
    give configure.