How to Stop a Shell Script with Ctl+c

Asked 1 years ago, Updated 1 years ago, 117 views

#!/bin/sh
param_list=("param1" "param2" "param3")
for parameter "${param_list[@]}"
do
  python sample.py $param
done

As you can see above, when you pass command line arguments to a file and run them with a for statement, you cannot get out of the loop once Ctl+c.What should I do?

shellscript

2022-09-30 21:16

3 Answers

Maybe it's because the Python interpreter traps the SIGINT signal by default and treats it as an exception within Python.

To set the operating system to its default behavior, you might want to set the handler to SIG_DFL in Python scripts.

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)


2022-09-30 21:16

Use trap on the shell script side.

trap 'exit1' INT


2022-09-30 21:16

Create a function that ends with a shell script and run trap

 function force_exit(){
    # Termination of something
    exit1
}

trap 'force_exit' 1 2 3 15


2022-09-30 21:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.