Add a confirmation dialog with bash

If you have a bash script doing some critical actions, it can be useful to add a confirmation dialog to double check with the user that he really wants to perform the action.

Here is a very simple script allowing this kind of checking:

#!/bin/bash
echo "Welcome to your favourite script!"
read -r -p "Are you sure you want to execute it? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
then
  echo "Execution in progress..."
  # Write your action here
else
  echo "Action canceled."
  exit
fi
echo "End of script."

Output will look like:

  • Case ‘yes’:
    $ bash script_yesno.sh 
    Welcome to your favourite script!
    Are you sure you want to execute it? [y/N] y
    Execution in progress...
    End of script.
    
  • Case ‘no’:
    $ bash script_yesno.sh 
    Welcome to your favourite script!
    Are you sure you want to execute it? [y/N] N
    Action canceled.
    

It’s up to you customizing it depending on your needs and your feelings!