Professor_Dodo
Professor_Dodo

Reputation: 99

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

Example:

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

A is exited via ctrl+C.

I didn't really know how to search for this.

Upvotes: 0

Views: 89

Answers (2)

Rodrigo V
Rodrigo V

Reputation: 101

The simplest way to do it is to trap the Ctrl+C signal to do nothing but pass the control to the shell script again. I tried the below code and it worked for me. Replace the sleep commands by the real commands you want to execute.

#!/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

More information can be find in the below links:

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

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295403

Use a custom handler for 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"

Replace sleep 30 and echo "running remander" with your real commands.

Upvotes: 1

Related Questions