2

I am working on some piece of python code that calls various linux tools (like ssh) for automation purposes. Right now I am looking into "return code" handling.

Thus: I am looking for a simple way to run some command that gives me a specific non-zero return code; something like

echo "this is a testcommand, that should return with rc=5"

for example. But of course, the above comes back with rc=0.

I know that I can call false, but this will always return with rc=1. I am looking for something that gives me an rc that I can control.

Edit: first answers suggest to exit; but the problem with that: exit is a bash function. So, when I try to run that from within a python script, I get "No such file or directory: exit".

So, I am actually looking for some "binary" tool that gives me that (obviously one can write some simple script to get that; I am just looking if there is something similar to false that is already shipped with any Linux/Unix).

1
  • How would you be running the command from Python? subprocess.Popen('exit 5', shell=True would work. Commented Sep 28, 2016 at 11:38

3 Answers 3

7

Run exit in a subshell.

$ (exit 5) ; echo $?
5
Sign up to request clarification or add additional context in comments.

3 Comments

That works nicely when I execute it directly within bash. But i need a command that python runs for me (like false). Any further thoughts are welcome.
In that case just invoke a shell in order to have it return the value. sh -c "exit 5"
Give or take some subtleties, in the cmd_str = "bash -c 'exit 5'" did the job! Thanks!
3

I have this function defined in .bashrc:

return_errorcode () 
{ 
    return $1
}

So, I can directly use something like

$ return_errorcode 5
$ echo $?
5

Compared to (exit 5); echo $? option, this mechanism saves you a subshell.

Comments

2

This is not exactly what you are asking but custom rc can be achieved through exit command.

 echo "this is a test command, that should return with " ;exit 5
 echo $?
 5

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.