Bash Script – Cancel Command Without Exiting Script

bash

When running a script with some lines not too important for the script to finish, how do I cancel a specific command without killing the entire script?

Normally I would invoke Ctrl+c, but when I do that with that script, the entire script ends prematurely. Is there a way (e.g. options placed inside the script) to allow Ctrl+c just for the command at hand?

A bit of a background:
I have my ~/.bash_profile to run ssh-add as part of it, but if I cancel it, I would like to get the echo lines following the "error 130" of ssh-add being shown to remind me to run it manually before any connection.

Best Answer

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.

Related Question