I have a script in which I'm meticulously checking return codes for error conditions, so that I can abort early in the event of a failure. One step of this script involves running a command as the root
user on another box, via ssh
and sudo
.
Consider:
ssh $HOST sudo $CMD
echo $?
ssh
passes return codes back just fine, but even if $CMD
returns a nonzero exit code, sudo
still returns 0 after running the command.
How do I capture the return code to $CMD
? I'm very partial to its being passed back as ssh
's return code, but if there's another simple method which can't be confused by the output of $CMD
, I'm all ears.
Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
Launch a terminal, and run any command. Check the value of the shell variable “$?” for the exit code. $ echo $? As the “date” command ran successfully, the exit code is 0.
Exit Codes. Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .
When running a command using subprocess.run(), the exit status code of the command is available as the .returncode property in the CompletedProcess object returned by run(): Copy from subprocess import run p = run( [ 'echo', 'Hello, world!' ] ) print( 'exit status code:', p.returncode )
Windows: Get Exit Code (ErrorLevel) – CMD & PowerShell. Every command or application returns an exit status, also known as a return status or exit code.
Every command or application returns an exit status, also known as a return status or exit code. A successful command or application returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. In Linux you can get the exit status of a last command by executing echo $?.
Get-Job -State Running # stop all running jobs Get-Job -State Running | Stop-Job # start job $p=Start-Job $job # wait for job to end Wait-Job -Name $p.Name $o=Receive-Job -Name $p.Name $o $o[0] This illustrates one way to get the exit code: use the stdout from the called script, then parse the output from Receive-Job.
As it turns out, sudo
is passing the return code properly. My test case very likely was overwriting $?
with a subsequent execution or conditional test. I normally use a named variable to preserve $?
to avoid such things, but there you are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With