2

I use the following pattern often:

some_long_running_command && echo success

However, sometimes I forget to attach the && success, so I write out the status check in the next line:

some_long_running_command
[ $? -eq 0 ] && echo success

As you can see, the status check in the second example ([ $? -eq 0 ] &&) is much more verbose than the check from the first example (&&).

Is there a more concise way to run a command only if the previous command completes successfully, when the previous command is already running?

2
  • 3
    You cannot check the status of the last command while it is running. You can only print the exit status after it is finished. The shortest would be echo $?. Alternatively, a classic approach would be to modify your prompt to contain the exit status (see here). This way you always see the exit status of the last command. Commented Feb 2, 2021 at 16:22
  • @kvantour - maybe question was unclear. I am trying run a new command conditionally if the previous command that is already running completes successfully. I have edited the question to improve clarity. Commented Feb 2, 2021 at 17:48

1 Answer 1

4

exit exits its shell using the same exit status as the most recently completed command. This is true even if that command runs in the parent of the shell that executes exit: you can run exit in a subshell.

some_long_running_command
(exit) && echo success

Depending on the command, you can also suspend the job, then resume it with fg, which will have the same exit status as the command being resumed. This has the benefit of not having to wait for the command to complete before adding the new && list.

some_long_running_command
# type ctrl-z here
fg && echo success

Generally, this will work as long as some_long_running_command doesn't have to keep track of some resource that is changing in real-time, so that you don't lose data that came and went while the job was (briefly) suspended.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.