How to use Ctrl+C to stop whole script not just current command

后端 未结 2 535
悲哀的现实
悲哀的现实 2021-02-18 14:43

I have a script such as follows:

for ((i=0; i < $srccount; i++)); do
    echo -e \"\\\"${src[$i]}\\\" will be synchronized to \\\"${dest[$i]}\\\"\"
    echo -         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-02-18 15:07

    Ctrl+C sends the interrupt signal, SIGINT. You need to tell bash to exit when it receives this signal, via the trap built-in:

    trap "exit" INT
    for ((i=0; i < $srccount; i++)); do
        echo -e "\"${src[$i]}\" will be synchronized to \"${dest[$i]}\""
        echo -e $'Press any key to continue or Ctrl+C to exit...\n' 
        read -rs -n1
        rsync ${opt1} ${opt2} ${opt3} ${src[$i]} ${dest[$i]}
    done
    

    You can do more than just exiting upon receiving a signal. Commonly, signal handlers remove temporary files. Refer to the bash documentation for more details.

提交回复
热议问题