Link to home
Start Free TrialLog in
Avatar of Swaminathan K
Swaminathan KFlag for India

asked on

output redirection using exec command

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.
Avatar of David Favor
David Favor
Flag of United States of America image

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

ASKER CERTIFIED SOLUTION
Avatar of noci
noci

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Swaminathan K

ASKER

getting an error invalid  file descriptor as i have closed it .I cannot use it .
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>&-
Avatar of noci
noci

looks a lot better.