0

I have a script that is rather "noisy". I've been asked to clean up the output so that most of the script's output goes to a log file, and the user just sees the start-up message, and the message when the script ends. To do this, I'm using exec like this:

#! /bin/bash
echo "Welcome! set up has begun, this may take a few moments..."
exec 3>&1 4>&2 1>> script.log 2>&1
# Call a bunch of other programs - stderr and stdout must
# be written to a log file to diagnose programs, but nothing out the console...
exec 1>&3 2>&4
echo "Your system is ready to use!"

I'm concerned though, about what will happen if one of the programs inside the logged portion of this script fails (I don't have much control over these programs) and causes the main script to fail. If the line exec 1>&3 2>&4 fails to execute, I'm worried the user could end up with stderr and stdout redirected, leaving their terminal unusable! Is there a safer way to handle this?

2

If the script is run as a separate program, then any redirections will not survive the end of the process; they'll apply only to the implicit /bin/bash yourscript.sh, not to the interactive shell the user is running. This is the normal case. The only way it could cause a problem is if the script were read in using source yourscript.sh or similar, which you shouldn't normally do.

  • Along with this, there's no need to actually copy standard output and error to 3 and 4 if you aren't going to use them. – chepner Sep 5 '15 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.