I'm working with a command, 'SomeCommand', that produces a bunch of output (15-20 lines) which the user needs to see. Usually, it fails in a predictable way. I'm trying to handle the output and check the exit code correctly using an if statement. My current setup is as follows: I'm using a combination of `tee` and `grep` to process the output, but I'm hitting a snag where my variable `$Xcode` ends up always being 0. This is an issue because I need to know if the exit code indicates a known or unknown error. I tested with 'true' and 'false', but can't seem to get the exit status correctly. Any suggestions or changes I should consider?
8 Answers
c
a
{
It looks like the backticks you're using for command substitution run the command in a subshell, which is why `$Xcode` is always 0. Instead, you might want to try this setup:
```bash
if SomeCommand | tee /dev/stderr | grep --quiet 'Known Error'; then
rc=${PIPESTATUS[0]}
# Known error handling
elif rc=${PIPESTATUS[0]}; (( rc > 0 )); then
# Unknown error handling
else
# No error
fi
```
This way, you can manage the exit statuses without running into that subshell issue! Plus, don’t forget to give `tee` the `-p` option; it might help you with proper file handling when redirecting output.
r
That's a cool trick! I didn't realize you could use it without `[...]`. I guess that simplifies a lot. I also figured out it was a subshell issue. I've switched to this approach: `Xcode=
SomeCommand | tee /dev/stderr | grep -c "Known Error" | tr -d 'n'; echo ${PIPESTATUS[0]}`. Using `tr` to strip newlines really helps!