允许在没有退出的shell脚本中使用ctrl + c终止可执行文件

时间:2015-06-16 15:21:33

标签: bash shell

示例:

#!/bin/bash
command_a    # starting a executable
command_b    # should be executed after after exiting A

A通过 ctrl + C 退出。

我真的不知道如何搜索这个。

2 个答案:

答案 0 :(得分:1)

为SIGINT使用自定义处理程序。

#!/bin/bash

# Set up a signal handler that kills current process
handle_sigint() { kill "$cur_pid"; }
trap handle_sigint INT

# Start first process, and store its PID...
sleep 30 & cur_pid=$!

# Wait for it to exit or be killed...
wait

# And run the second process.
echo "running remainder"

用您的真实命令替换sleep 30echo "running remander"

答案 1 :(得分:1)

最简单的方法是捕获Ctrl + C信号,除了将控制再次传递给shell脚本之外什么都不做。 我尝试了下面的代码,它对我有用。通过要执行的实际命令替换sleep命令。

#!/bin/bash

#Trap the Ctrl+C signal to do nothing but pass the control to the script. 
trap : INT

#Executes command A.
echo "Executing command A. Hit Ctrl+C to skip it..."
sleep 10

#Reset trap of Ctrl+C.
trap INT

#Executes command B.
echo "Executing command B. Ctrl+C exits both command and shell script."
sleep 10

更多信息可在以下链接中找到:

https://unix.stackexchange.com/questions/184124/on-ctrlc-kill-the-current-command-but-continue-executing-the-script

https://unix.stackexchange.com/questions/57940/trap-int-term-exit-really-necessary