0

I'm running the following bash script to restart my Perforce server whenever it crashes, but what I want to do is make it so the bash script runs a Python script to send a webhook with the exit code of the application to my Slack channel.

The Python script allows you to do something like python app.py 225 and it works, but what I want to do is pass $? into that script, such as python app.py $?.

Whenever the service restarts the echo line reports the exit code properly (In the terminal it shows 225), but when passed into the Python script $? appears as 0.

#!/bin/bash

until ~/Desktop/shell/p4d; do
    echo "Perforce Server crashed with exit code $?.  Respawning.." >&2
    sleep 1
    python ~/Desktop/shell/app.py $?
done

Snippet of the Python script which fetches the argument:

if __name__ == "__main__":
    error = str(sys.argv[1])
    print error
    post_message(error)

How would I do this?

4
  • Well, $? will hold 0 as sleep 1, presumably, exited with exit code 0... Bash is quirky that way ;) Commented Jun 6, 2017 at 14:51
  • $? in the example is the exit code of sleep 1 rather than p4d. Store it as a variable just inside the until loop ftw Commented Jun 6, 2017 at 14:54
  • Kidding aside, here is a great answer on what's going on. Commented Jun 6, 2017 at 14:56
  • I suppose the part I'm not understanding is why that value is 0 when it's passed into the Python script, but gets echo'd as something completely different in the terminal. Commented Jun 6, 2017 at 14:58

1 Answer 1

2

The $? behaves like a variable. After each call to an program (e.g. p4d, sleep, python), the return value of that command is stored in $? by bash.

In your case, $? contains the return value of p4d, when you "echo" it. Afterwards you call the "sleep", which is actually a program "/bin/sleep", so the value of $? gets replaced by the return code of sleep, which is 0. Therefore the python script gets called with "0" as well.

To solve your problem, you could cache the return code in a local variable, like this:

#!/bin/bash

until ~/Desktop/shell/p4d; do
    P4D_RETURN=$?
    echo "Perforce Server crashed with exit code $?.  Respawning.." >&2
    sleep 1
    python ~/Desktop/shell/app.py $P4D_RETURN
done
Sign up to request clarification or add additional context in comments.

1 Comment

Makes perfect sense!

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.