We help IT Professionals succeed at work.

output redirection using exec command

sam_2012
sam_2012 asked
on
57 Views
Last Modified: 2018-11-15
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

David FavorFractional CTO
CERTIFIED EXPERT
Distinguished Expert 2019

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
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

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
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
looks a lot better.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions