Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Shell 腳本中的 2>、>&2 與 &> 重定向用法

Linux 標準文件描述符:

文件描述符 縮寫  描述

0  STDIN 標準輸入

1  STDOUT 標準輸出

2  STDERR 標準錯誤

標準輸入與標準輸出,指的就是鍵盤與螢幕。

當文件描述符(0、1、2)與重定向符號(<)組合之後,就能重新定向輸入、輸出及錯誤。

  • command 2>file1
    • 命令執行的錯誤資訊被保存到 file1 中,螢幕只顯示正確資訊。
  • command 1>file1 2>file2
    • 命令執行後沒有任何顯示,因為正確輸出導向 file1,錯誤導向 file2。
  • command &>file1
    • 命令執行後,輸出與錯誤都導向 file1。

在 shell 腳本中,可以把「錯誤」輸出導向 STDERR 指定的檔案,需要在重定向符與文件描述符之間加一個 and 符(&):

  1. cat test
  2. #!/bin/bash
  3. echo " this is ERROR ">&2
  4. echo "this is output"
  5. $

運行腳本:

  1. [root@localhost ~]#./test 2>file1
  2. thisis output
  3. [root@localhost ~]# cat file1
  4. thisis ERROR

也可以在腳本中使用 exec 命令:

  1. exec1>file1
  2. exec2>file2
  3. echo " this is ERROR ">&2
  4. echo "this is output"

運行如上腳本,輸出便都進入了 file1 與 file2。

同樣地,也能用 exec 0<file1 從 file1 中讀取輸入。

Copyright © Linux教程網 All Rights Reserved