5

I don't know why I can't trap Ctrl^C in this simple script.

#!/bin/bash

for number in $(seq 10); do
        echo -n "."
        sleep 2
done

function finish() {
        echo "bye."
}

trap finish SIGINT

I've tried using INT instead of SIGINT, without success.

SOLVED:

Ok. Order is important.

#!/bin/bash

function finish() {
        echo "bye."
}

trap finish SIGINT

for number in $(seq 10); do
        echo -n "."
        sleep 2
done

That worked.

5

Answer inspired by edit to OP. Please don't kill me...


Order in scripting is pretty important. First off, you need to put the function first. You also need to put the trap before the loop. Something like this should work well:

#!/bin/bash

function finish() {
        echo "bye bye!"
}

trap finish SIGINT

for number in $(seq 10); do
        echo "TODO: Insert work here..."
        # Insert work to do here.
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.