簡體   English   中英

為什么在我關閉文件描述符並想要回顯一些文本后,我有錯誤的文件描述符?

[英]Why do I have and error bad file descriptor after I close my file descriptor and want to echo some text?

我想在 if 條件下重定向文本。 我打開兩個文件描述符並關閉它們。 一切正常,結果被重定向到文件。 但是當我想在 if 條件之后回顯一些文本時,它會拋出一個錯誤:錯誤的文件描述符。 怎么了?

echo "Enter the number between 5 and 10"
read number

if  [[ $number -le 5 || $number -ge 10 ]]

 then
    
echo "There is an error!"
    
#open file descriptor

    exec 2>error.txt
    echo "---------------------" >&2
    echo "Your answer is $number" >&2
    echo "I wanted you to enter number between 5 and 10!" >&2
    exec 2>&-
else
    
echo "You are really good!"

    #open file descriptor

    exec 1>output.txt
    echo "---------------------"
    echo "You are so cool! Your answer is correct!"
    echo "Your answer was $number"
    exec 1>&-
fi

echo "Some text"

1是標准 output 的文件描述符。 默認情況下,任何命令(如echo寫入標准 output)。 >之前沒有數字的>重定向,例如>&3正在重定向命令的標准 output,重定向第一個文件描述符。 IE。 echo >&3完全等於echo 1>&3

使用exec 1>&-關閉標准 output 后,然后寫入標准 output 的下一個命令(如echo "Some text"將出錯 - 因為標准 Z78E6221F6393D1356681DB398F14CED 已關閉

因此,對於自定義文件描述符,請使用大於或等於3的數字,以免干擾標准 output 1或標准錯誤2

但是......只需將語句分組:

{
   echo "---------------------"
   echo "Your answer is $number"
   echo "I wanted you to enter number between 5 and 10!" 
} > error.txt

在重定向標准 stream 之前,您可以復制它

exec 3>&1    # fd 3 is now a copy of fd 1

# change fd 1
exec 1>output.txt
echo some text goes to the output file

# restore fd 1
exec 1>&3 3>&-
echo some text goes to stdout

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM