How to cancel a command inside a script without exiting the script itself?

I think you are looking for traps:

trap terminate_foo SIGINT

terminate_foo() {
  echo "foo terminated"
  bar
}

foo() {
  while :; do 
    echo foo
    sleep 1
  done
}

bar() {
  while :; do 
    echo bar
    sleep 1
  done
}

foo

Output:

./foo
foo
foo
foo
^C foo terminated # here ctrl+c pressed
bar
bar
...

Function foo is executed until Ctrl+C is pressed, and then continues the execution, in this case the function bar.


#! /bin/bash

trap handle_sigint SIGINT

ignore_sigint='no'

handle_sigint () {
        if [ 'yes' = "$ignore_sigint" ]; then
                echo 'Caught SIGINT: Script continues...'
        else
                echo 'Caught SIGINT: Script aborts...'
                exit 130 # 128+2; SIGINT is 2
        fi
}

echo 'running short commands...'
sleep 1
sleep 1

ignore_sigint='yes'
echo 'running long commands...'
sleep 10
ignore_sigint='no'
echo 'End of script.'

Tags:

Bash