天天看點

1>&2, 2>&1, &>

進行一個标準輸出、标準錯誤輸出分流的試驗:

edemon@ubuntu1:~/workspace$ ./test.sh
hello world
./test.sh: line 3: pt: command not found
edemon@ubuntu1:~/workspace$ ./test.sh 1>out 2>err
edemon@ubuntu1:~/workspace$ vim -O out err
2      

現在嘗試直接重定向标準錯誤到标準輸出:

​​

​edemon@ubuntu1:~/workspace$ ./test.sh 2>1​

但是很遺憾,出現這樣的結果:

​​

​hello world​

接着我們能發現一個新的文本1,并在檔案1中發現錯誤資訊。

bash将1當做了一個普通檔案。

使用​​

​2 >& 1​

​是為了避免這樣的壞事發生。

edemon@ubuntu1:~/workspace$ ./test.sh 2 >& 1
hello world
./test.sh: line 3: pt: command not found
# 或者改成:
edemon@ubuntu1:~/workspace$ ./test.sh 2>/dev/stdout
hello
./test.sh: line 3: pt: command not      

能在2的前面加上&嗎?不能,bash會将sh腳本在背景執行。

edemon@ubuntu1:~/workspace$ ./test.sh &2 >& 1
[1] 3497
hello world
./test.sh: line 3: pt: command not found
2: command not found
[1]+  Exit 127      

總結:

1和2是檔案描述符,而不是檔案,需要加上&告訴bash。

例如:

$ cat read
this is a story about hero
text block

# 建立檔案描述符3
$ exec 3<read

$ ls
#沒有産生檔案3
checkRoot.sh  delete.sh  envi.sh  interc.sh  output.sh  read  read1  strlen.sh  test.sh

$ cat <&3
this is a story about hero
text      

1>&2 意思是把标準輸出重定向到标準錯誤.

2>&1 意思是把标準錯誤輸出重定向到标準輸出。

​&>​

​​是​

​2>&1 >​

​的縮寫

&>filename 意思是把标準輸出和标準錯誤輸出都重定向到檔案filename中

例如:

$ cat read 2>&1 > read1
$ cat read1
this is a story about hero
text block

$ cat /dev/null > read1

$ cat read &> read1
$ cat read1
this is a story about hero
text