I have a rather complicated series of commands in bash that returns a returning meaningful exit code. In different places in the script, it is necessary to divide conditionally on whether the set of commands has been successfully installed.
I am currently saving the exit code and checking it numerically, something like this:
long_running_command | grep -q trigger_word status=$? if [ $status -eq 0 ]; then : stuff else : more code if [ $status -eq 0 ]; then : stuff else
For some reason, it seems like it should be easier. We have a simple exit code, and now we repeatedly type in numerical test operations to run it. For example, I can deceive the use of string output instead of a return code, which is easier to check for:
status=$(long_running_command | grep trigger_word) if [ $status ]; then : stuff else : more code if [ $status ]; then : stuff else
On the surface, it looks more straightforward, but I understand that it is dirty.
If the other logic were not so complicated, and I only ran it once, I understand that I can embed it instead of the test operator, but this is not ideal when you need to reuse the results in other places without restarting the test :
if long_running_command | grep -q trigger_word; then : stuff else
The only thing I have found so far is code assignment as part of command substitution:
status=$(long_running_command | grep -q trigger_word; echo $?) if [ $status -eq 0 ]; then : stuff else
Even this is technically not a one-time assignment (although some may argue that readability is better), but the necessary numerical testing syntax still seems cumbersome to me. Maybe I'm just an OCD.
Am I missing a more elegant way to assign an exit code to a variable and then step into it later?