linux bash關閉標准輸出1(exec 1<&-)后重新打開


linux bash shell的再次學習。

文件描述符:

stdin,stdout 和 stderr 的文件描述符分別是 0,1 和 2(一個文件描述符說白了就是文件系統為了跟蹤這個打開的文件而分配給它的一個數字)

1 .避免管道產生的子shell

 #!/bin/bash
 
 E_WRONG_ARGS=71
 if [ -z "$1" ]
 then
     echo "Usage: $0 input-file"
     exit $E_WRONG_ARGS
 fi
 
 Lines=0
 
 cat "$1" | while read line; # 管道會產生子 shell
 do {
     echo $line
     (( Lines++ )); #  增加這個變量的值
     # 但是外部循環卻不能訪問
 }
 done
 
 echo "Number of lines read = $Lines" # 0
 # 錯誤!
 echo "------------------------"
 exec 3<> "$1"
 while read line <&3
 do {
     echo "$line"
     (( Lines++ )); #  增加這個變量的值
     # 現在外部循環就可以訪問了
     #  沒有子shell, 現在就沒問題了
 }
 done
 exec 3>&-
 echo "Number of lines read = $Lines"
 exit 0
                                                                             

  

 

2.綁定屏幕的便准輸出到 out這個文件,即將所有的標准輸出都輸出到out這個文件當中。

 

--------------------------------------------------

參考:https://www.cnblogs.com/sparkdev/p/10247187.html

這樣子來讀入文件fly的內容

 清空文件

 

----------------------------------------------------------------------------

Reopen STDOUT and STDERR after closing them?

I am running this on an Ubuntu machine, so I am not sure if it'll work for you, but this is what I did:

$ exec 1>&0 $ exec 2>&0

Suddenly, I had STDOUT and STDERR reconnected. Magic!

Explanation: Running the following commands, we get the following output:

$ ls -l /dev/stdout lrwxrwxrwx 1 root root 15 Jun 11 23:39 /dev/stdout -> /proc/self/fd/1 $ ls -l /proc/self/fd/1 lrwx------ 1 jay jay 64 Jun 22 01:34 /proc/self/fd/1 -> /dev/pts/10 $ ls -l /proc/self/fd/ total 0 lrwx------ 1 jay jay 64 Jun 22 01:35 0 -> /dev/pts/10 lrwx------ 1 jay jay 64 Jun 22 01:35 1 -> /dev/pts/10 lrwx------ 1 jay jay 64 Jun 22 01:35 2 -> /dev/pts/10 lr-x------ 1 jay jay 64 Jun 22 01:35 3 -> /proc/12224/fd

Since all three fd's point to the same thing, we can return them back to normal just by pointing to /dev/pts/10 which the exec 1>&0 and exec 2>&0 do


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM