Add Docker bash exit prompt to prevent accidental data loss during container preparation

0.00 avg. rating (0% score) - 0 votes

During the development of my Docker container image running on Ubuntu, I often type exit after making changes to my container, without also typing docker commit (from a separate shell session) to save the changes back to the container image. Since Docker containers are by default ephemeral, e.g. immutable or read-only, changes will be discarded upon exit unless docket commit is used. To prevent this, I add a prompt asking if the user really wants to exit. This way, at least, any changes won’t be accidentally lost just because the exit command is used.

Implementing such a prompt is trivial by editing ~/.bashrc which points to /home/.bashrc on my installation to implement a custom exit() function. The function will add a prompt (or in my case, a double prompt which asks the user to confirm twice) when exit is executed, and only proceed to exit if confirmation is received from the user:

exit() {
    echo -n "Please commit all Docker changes first. Otherwise, all changes will be lost. Are you sure you want to exit? [y/N] "
    read -n 1 -r REPLY
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Exit cancelled."
        return
    fi

    echo -n "Waiting for a while before asking you again... "
    sleep 10
    echo -n "Again, please commit all Docker changes first. If not, you might lose data. Are you sure you want to exit? [y/N] "
    read -n 1 -r REPLY
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Exit cancelled."
        return
    fi

    # Call the original exit command
    command exit
}

Save the changes by running docker commit (from a separate bash shell), then type exit to exit the Docker session. Start the Docker image again, for example with sudo docker run -ti –rm ubuntu /bin/bash, and type exit. You will be asked to confirm that you have already committed the changes, twice, before you can exit. The double prompt with a delay is needed to prevent me from habitually answering yes to the question:

Screenshot 2024-10-22 234849

This way, I can be sure that I will always remember to commit my changes before exiting, and that no changes will be lost simply because the session has been accidentally closed with the exit command.

0.00 avg. rating (0% score) - 0 votes
ToughDev

ToughDev

A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>