歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell腳本中的“2< " ">&2" "&>”

shell腳本中的“2< " ">&2" "&>”

日期:2017/3/1 9:41:44   编辑:SHELL編程

Linux標准文件描述符:

文件描述符 縮寫 描述 0 STDIN 標准輸入 1 STDOUT 標准輸出 2 STDERR 標准錯誤

標准輸入和標准輸出指的就是鍵盤和顯示器。

Linux Shell參數替換 http://www.linuxidc.com/Linux/2013-06/85356.htm

Shell for參數 http://www.linuxidc.com/Linux/2013-07/87335.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

當文件描述符(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,從文件1中讀取輸入。

Copyright © Linux教程網 All Rights Reserved