I'm writing a script that takes files (
filename...) as arguments, and redirects both the stdout and stderr to a file of name
filename.output. In the files are commands, and I'd only like to bash once (in case a command within a file should not be run multiple times i.e.
rmdir). I have found that, when iterating through the arguments, this command works:
bash $a &> "$(basename $a).output"
However, I'd also like to use the error status of this command in case
.output could not be created for whatever reason:
if ! bash $a &> "$(basename $a).output" then echo >&2 "failed to create $(basename $a).output" fi
When I do this, my if statement always evaluates to true, which I think is because either stdout or stderr need to fail in redirecting, as opposed to both of them. Very few of the commands I am testing with produce both stderr and stdout (i.e. a command like
date produces stdout, but no stderr, thus causing a non-zero return value as stderr fails to redirect).
Am I correct in my analysis of why my code is not functioning properly, and if so, is there a way to check for the failure of stdout redirection and stderr redirection individually, so I accurately display when
.output isn't created?
EDIT: I have found that the issue actually lies in the
bash "$a" component, as any time
$a is a file with a command that produces an error, the overall if statement evaluates to true. I suppose now my question would be, are there any instances in which redirecting stdout and stderr would result in an error that I should look out for?