Linux – How to return a specific exit code on the Linux command line

bashlinux

I've got a program that controls a long-running process which runs over ssh on a remote machine. Frequently, I'll get disconnected in the middle of the process, so I've changed the invocation from something like this:

my-long-cmd

to

my-long-cmd; echo $? > /tmp/my.cmd.status

This works; the process itself kicks off a number of subprocesses and the like, so even if the connection gets disrupted it continues running, and my script can periodically reconnect to the machine and check if the file exists (and thus, the machine is finished provisioning), and if so see whether it exited successfully or not.

However, it also means if I don't get disconnected, I'll always only see the exit status of the echo command over the ssh library. I tried doing something like echo $? && return $? but return only works in scripts. Is there an easy way to do this?

Best Answer

Use exit followed by the value you want. Zero is considered success, non-zero failure. This is typically used within a script, and terminates the (sub)shell it is exited from.

If you want to capture the status of a command, assign $? to a variable. This allows you to save the value after displaying it.