我想在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"发布于 2020-07-19 21:30:13
1是标准输出的文件描述符。默认情况下,任何像echo这样的命令都会写入标准输出。在>前没有数字的>重定向,如>&3,是重定向命令的标准输出,重定向第一个文件描述符。即。echo >&3与echo 1>&3完全相等。
在你用exec 1>&-关闭标准输出之后,下一个像echo "Some text"这样写入标准输出的命令将会出错--因为标准输出被关闭了。
因此,对于自定义文件描述符,请使用大于或等于3的数字-这样就不会干扰标准输出1或标准错误2。
但是..。只需对语句进行分组:
{
echo "---------------------"
echo "Your answer is $number"
echo "I wanted you to enter number between 5 and 10!"
} > error.txt发布于 2020-07-19 21:26:41
在重定向标准流之前,您可以对其进行复制
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 stdouthttps://stackoverflow.com/questions/62980559
复制相似问题