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.
No such file or directory
comes back from the execve() syscall, which takes place after thefork()
and all the file descriptor redirection already happened. I don't see an obvious way to implement a shell that doesn't have this behavior, at least without creating a hard dependency on an operating system havingO_CLOEXEC
to maintain a separate mechanism for passing errors back over a FIFO that gets automatically closed on a successful exec.myexec > logfile 2>&1 && echo "ok" >&2 || echo "nope." >&2
.