How to Create Interactive Bash Scripts With Yes, No, Cancel Prompt in Linux

Interactive bash scripts can be a great way to engage users and provide them with options while running a script in Linux. Using prompts such as "yes," "no," and "cancel" can make the script more user-friendly and allow users to make decisions based on their preferences. In this article, we will discuss how to create interactive bash scripts with a yes, no, cancel prompt in Linux.

To begin, open a text editor and create a new bash script file. You can do this by typing the following command in the terminal:

nano interactive_script.sh

Next, add the following code to the script file:

#!/bin/bash

# Prompt the user with a yes, no, cancel prompt
echo "Do you want to continue? (yes/no/cancel)"
read choice

# Check the user's response and perform actions accordingly
if [ "$choice" == "yes" ]; then
    echo "You chose yes. Continuing..."
    # Add your commands here
elif [ "$choice" == "no" ]; then
    echo "You chose no. Exiting..."
    exit
elif [ "$choice" == "cancel" ]; then
    echo "You chose cancel. Aborting..."
    exit
else
    echo "Invalid choice. Please choose yes, no, or cancel."
fi

In this script, we prompt the user with a question and read their response using the read command. We then use an if statement to check the user’s response and perform actions accordingly. If the user chooses "yes," we display a message and continue with the script. If they choose "no," we exit the script. If they choose "cancel," we also exit the script. If the user enters an invalid choice, we display an error message.

Save the script file and make it executable by running the following command in the terminal:

chmod +x interactive_script.sh

You can now run the script by typing the following command:

./interactive_script.sh

The script will prompt the user with a yes, no, cancel prompt and wait for their response. They can enter "yes," "no," or "cancel" to make their choice. Depending on their input, the script will perform the corresponding action.

Creating interactive bash scripts with a yes, no, cancel prompt can enhance the user experience and provide them with options to make decisions while running a script in Linux. By following the steps outlined in this article, you can easily create interactive bash scripts with prompts in Linux.