Avatar of Swaminathan K
Swaminathan K
Flag 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.
Linux

Avatar of undefined
Last Comment
noci

8/22/2022 - Mon
David Favor

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
noci

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Swaminathan K

ASKER
getting an error invalid  file descriptor as i have closed it .I cannot use it .
Swaminathan K

ASKER
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>&-
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
noci

looks a lot better.