簡體   English   中英

允許在不退出的Shell腳本中使用ctrl + c終止可執行文件

[英]Allowing an executable to be terminated w/ ctrl+c in a shell script w/o exiting

例:

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

A通過ctrl + C退出。

我真的不知道該如何搜索。

對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 30並用實際命令echo "running remander"命令”。

最簡單的方法是捕獲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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM