ben-albrecht
ben-albrecht

Reputation: 1865

Concise way to run command if previous command completes successfully, when previous command is already running

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?

Upvotes: 2

Views: 1214

Answers (1)

chepner
chepner

Reputation: 531125

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.

Upvotes: 4

Related Questions