天天看點

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

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

linux标準檔案描述符:

檔案描述符

縮寫

描述

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符(&)

cat test

#!/bin/bash

echo " this is error "   >&2

echo  "this is output"

$

運作腳本

[root@localhost ~]# ./test 2>file1

this is output

[root@localhost ~]# cat file1

this is error

可以再腳本中使用exec指令:

exec 1>file1

exec 2>file2

運作如上腳本,則輸出都在file1和file2中。

也可以使用exec 0<file1,從檔案1中讀取輸入。

原文釋出時間:2014-07-25

本文來自雲栖合作夥伴“linux中國”

繼續閱讀