output redirection using exec command

sam_2012
sam_2012 used Ask the Experts™
on
Hi team,

below is the program i have written to redirect the output to file using my own file descriptor. Iam able to successfully redirect the output to a file .
But the problem iamm facing is that , after closing my file descriptor still my programs writes the output to the file

How to solve this problem , any help is really appreciated


#script5
#!/bin/bash
#script to create our own file descriptor

exec 4>fileout
#redirect standard output to file descriptor 4

exec 1>&4
echo "This is a test program"
exec 4&-

echo " Back to normal"

# i want the output back to normal to be displayed on the screen , but it is getting stored in the file

Any help is really appreciated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David FavorFractional CTO
Distinguished Expert 2018

Commented:
You'll end up with far more robust code by simply doing an echo to a specific file number, rather than trying to merge/unmerge various file numbers...

Using exec is far more complex than docs suggest. Try this instead...

echo "This is a test program" >&4

Open in new window

Software Engineer
Distinguished Expert 2018
Commented:
exec 4>fileout
exec 1>&4
echo "This is a test program"


This assign the FD=4 to fileout
then it dup()'s  FD=4 to FD=1 (closing original FD=1)
exec 4&-

Will dup() FD=4 to another FD>10.    (oh btw.   there needs to be a > or < with &-...)
There is nothing that will bring the original fd=1 back.


echo >fileout "This should be in Fileout"
echo "and this not"

should work a lot better...
Otherwise you need a subshell. / different shell

Author

Commented:
getting an error invalid  file descriptor as i have closed it .I cannot use it .

Author

Commented:
Thanks noci and david , below is the code iam implemented
now it is working

script5
#!/bin/bash
#script to create our own file descriptor

exec 4>fileout
exec 5>&1
#redirect standard output to file descriptor 4

exec 1>&4
echo "This is a test program"
exec 4>&-
exec 1>&5
echo " Back to normal"
exec 5>&-
nociSoftware Engineer
Distinguished Expert 2018

Commented:
looks a lot better.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial