Dari V
Dari V

Reputation: 43

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

I wanted to redirect text in if condition. I open two file descriptors and I close them. Everything is working, and the result was redirected to the file. But when I want to echo some text after if condition, it throws an error: bad file descriptor. What's wrong?

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"

Upvotes: 1

Views: 3786

Answers (2)

KamilCuk
KamilCuk

Reputation: 140880

1 is the file descriptor for standard output. Any command like echo write to standard output by "default". A > redirection without a number before the >, like >&3 is redirecting standard output of a command, redirecting first file descriptor. Ie. echo >&3 is exactly equal to echo 1>&3.

After you close standard output with exec 1>&- then the next command that writes to standard output like echo "Some text" will error - because standard output is closed.

So for custom file descriptors use numbers greater or equal to 3 - so not to interfere with standard output 1 or standard error 2.

But... just group the statements:

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

Upvotes: 3

glenn jackman
glenn jackman

Reputation: 246744

before redirecting a standard stream, you can make a copy of it

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

Upvotes: 2

Related Questions