2

pseudo code in my xxx.sh

a large loop {
    python xxx.py
}

when I run this script ./xxx.sh and some bugs in python, then exception info will be raised to stdout repeatedly.

if I press ctrl+c, the signal will be catched by python, and if I press ctrl+z, the xxx.sh will be sleep in the background.

So, I am trying to add some trap code to catch ctrl+z, the trap code in my xxx.sh

function stop_ctrl_z() {
    echo $$
    pkill -9 $$
}
trap stop_ctrl_z SIGTSTP

But xxx.sh cannot stop itself when met ctrl+z as my expected.

It hangs up, sadly I must open another terminal and use pkill -9 xxx.sh to stop this script.

^Z^Z^Z^Z^Z^Z^Z^Z^Z^Z

Does someone has solution to solve my problem?

Allan
  • 12,117
  • 3
  • 27
  • 51
myanl
  • 135
  • 1
  • 9

1 Answers1

1

Just force an exit when the Python call fails:

python xxx.py || exit 1

You could use break instead of exit to just leave the loop. More advanced error handling can be achieved by evaluating $?; here's an example how to store the return value and reuse it:

python xxx.py
result=$?
if [ ${result} -ne 0 ]; then
    # Error
    echo "xxx.py exited with ${result}"
    ...
else
    # Success
    ...
fi

As a general rule, not only regarding Bash scripting but programming in general, always check return codes of commands for errors and handle them. It makes debugging and your working life in general easier in the long run.

Murphy
  • 3,827
  • 4
  • 21
  • 35
  • You should basically never need to compare `$?` to zero explicitly in a conditional. The *purpose* of `if` is to run a command and check its exit code. If it is zero, the `then` code path is taken; otherwise, the `else` path, if present. – tripleee Jan 30 '18 at 10:20
  • @tripleee The intention of my example is to show the reuse of the return value, which otherwise would be lost with the next command. It could be shortened, but wouldn't gain in readability by that. Don't hesitate to provide your own answer and example if you think it's more helpful for the OP's issue. – Murphy Jan 30 '18 at 10:24
  • `python xxx.py || exit` propagates the error to the caller. If you really need to keep the result code, you can capture it inside the `else` clause. (It will obviously be zero in the `then` clause.) – tripleee Jan 30 '18 at 10:28
  • @Murphy Sorry for the late reply, actually, my python xxx.py would run fail, and I want to rerun it if $? is not 0. Is there any way both to handle rerun if $? is not 0 and ctrl+z which I really want to stop it? – myanl Feb 05 '18 at 03:02