76 Pinto
76 Pinto

Reputation: 21

Redirect an executable's stdout/stderr but not invocation-time errors from the shell

I have a simple bash script that launches an executable in the background and redirects stdout + stderr to a log file:

#!/usr/bin/bash
myexec >& logfile &

It works. However, output from myexec isn't the only thing that gets redirected: any messages that bash emits while attempting to invoke myexec are also going to logfile. To wit, if bash doesn't find myexec, I don't get to see the myexec: No such file or directory error because it went straight to logfile instead of to the terminal. This behavior annoys me because I end up not knowing whether the script succeeded in starting up myexec.

It occurs to me that the script could just test for the existence of myexec before trying to invoke it, but I'm wondering whether there isn't a way to do the redirection itself in such a way that only myexec's output, and not the shell's, gets redirected.

Upvotes: 1

Views: 146

Answers (1)

76 Pinto
76 Pinto

Reputation: 21

It's not possible to separate the outputs in the way the OP describes. As Charles Duffy explains in his comment, the system call that opens (or fails to open) the executable myexec takes place after Bash has forked a new process, at which point all of the I/O redirection has already been set up. There is, however, a workaround that suffices for the purpose stated in the OP, namely, "knowing whether the script succeeded in starting up myexec":

myexec > logfile 2>&1 && echo "ok" >&2 || echo "nope." >&2

Upvotes: 1

Related Questions