Reputation: 3365
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?
Upvotes: 0
Views: 57
Reputation: 36
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
Upvotes: 2