1

Is it possible to get out of a bashscript while loop with CTRL+C and continue in the script instead of exiting it? In my script I have a while function and an menu function. I want to re-run the menu function if CTRL+C is pressed from the running while loop.

#!/bin/bash

function while_loop {
D=1
while [ "1" == $D ]
do
        sleep 5
        echo $D
done
}


function main_menu {
M="i"
while [ "$M" != "e" ]; do
echo -e "auto update:\ta"
echo -e "exit:\t\te"
read -n 1 M
case $M in
    a)  while_loop
        ;;
    e)
        exit 1
        ;;
    *)
        echo "Wrong input!"
esac
done
}

main_menu

1 Answer 1

1

Untested, but something like this

trap my_handler INT
my_handler() { D=0; }

The trap command allows you to intercept signals and add your own signal handling.

Sign up to request clarification or add additional context in comments.

1 Comment

I think that the call to sleep is preventing this from working as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.