Home Bash scripting How To Create Interactive Bash Scripts With Yes, No, Cancel Prompt In Linux

How To Create Interactive Bash Scripts With Yes, No, Cancel Prompt In Linux

By sk
1.8K views

Interactive shell scripts can make system administration tasks more efficient and user-friendly. By incorporating Yes, No, and Cancel prompts, you can ensure that scripts execute only with explicit user confirmation, preventing unintended actions. In this guide, we'll learn how to create interactive Bash scripts using Yes, No, and Cancel prompts in Linux.

Introduction

When you write Bash shell scripts, you can make them more useful by asking the user for input. This makes the script more interactive and user-friendly.

One way to do this is by using the read command, which allows you to prompt the user for input and store their response in a variable.

By combining the read command with conditional statements, such as if and case statements, you can make your script take different actions based on the user's response.

In this tutorial, we'll cover:

  • What is read command,
  • How to use the read command to capture user input,
  • Using if and case statements to handle different responses,
  • And practical examples for creating interactive Bash scripts.

By the end of this guide, you'll be able to write interactive Bash scripts that can prompt users to proceed, abort, or cancel operations.

What is read Command in Bash?

The read command in Bash is used to read a line of input from the user or from a file and assign it to one or more variables. This command is very useful in shell scripting for getting user input or processing text files.

How read Command works

When you use read, the script stops and waits for the user to type something and press Enter. Whatever the user types is saved in a variable that you can use later in your script.

Why is it useful?

  • It makes your scripts interactive.
  • You can get information from the user to customize how your script works.
  • It's great for creating menus or asking for confirmation before doing something important.

Examples of use

  • Asking for a user's name to personalize messages.
  • Getting a yes/no answer before proceeding with an action.
  • Creating a simple menu where users can choose options.

Basics of the read Command

1. Syntax:

read [options] variable_name

Options:

  • -r: Prevents backslashes from being interpreted as escape characters. Example: read -r response
  • -p: Lets you show a prompt message without needing echo. Example: read -p "What's your name? " name
  • -s: Hides what the user types (good for passwords). Example: read -s -p "Enter your password: " password
  • -t: Sets a time limit for the input.
  • -n: Limits the number of characters the user can input.

2. Reading User Input:

The most common use of the read command is to prompt the user for input during script execution.

Have a look at the following example:

echo "Please enter your name:"
read name
echo "Hello, $name!"
Reading User Input
Reading User Input

Here,

  • echo "Please enter your name:" displays a prompt message.
  • read name waits for the user to type something and press Enter. The input is stored in the variable name.
  • echo "Hello, $name!" displays the user's input back to them.

3. Using a prompt:

You can use -p option to display a prompt with using using echo command

read -p "How old are you? " age
echo "I am $age years old."
Using a Prompt
Using a Prompt

4. Reading Multiple Variables:

You can read multiple inputs into different variables in a single line.

echo "Enter your first name and last name:"
read first_name last_name
echo "Hello, $first_name $last_name!"
Reading Multiple Variables
Reading Multiple Variables

Here's an another example for reading multiple values:

read -p "Enter your favorite color and animal: " color animal
echo "Your favorite color is $color and your favorite animal is $animal."

5. Using a Default Value:

You can provide a default value if the user does not input anything.

read -p "Enter your favorite blog [OSTechNix]: " blog
blog=${blog:-OSTechNix}
echo "My favorite blog is $blog."
Using a Default Value
Using a Default Value

6. Setting a Time Limit for Input:

You can set a time limit for user input with -t flag like below:

read -t 5 -p "Quick! Type your lucky number (5 seconds): " lucky_number
echo "Your lucky number is $lucky_number"

If you don't enter an input within 5 seconds, the read command will simply exit.

Setting a Time Limit for Input
Setting a Time Limit for Input

7. Reading a Password (input is hidden):

You can use -s flag for getting sensitive information like passwords. You will not see any inputs as you type the password. Just type the password anyway and hit ENTER.

read -s -p "Enter a password: " password 
echo # This just prints a newline
echo "Password received (but not shown for security)"

Here's sample snippet of the read command to prompt the user to confirm whether to proceed with a system update, abort, or cancel the operation:

prompt_for_input() {
    while true; do
        echo -n "Do you want to update the system? (y/n/c): "
        read -r response
        case "$response" in
            [Yy]* )
                echo "You selected Yes."
                return 0
                ;;
            [Nn]* )
                echo "You selected No."
                return 1
                ;;
            [Cc]* )
                echo "You selected Cancel."
                return 2
                ;;
            * )
                echo "Invalid input. Please enter y, n, or c."
                ;;
        esac
    done
}

Here's what the above script does:

  • echo -n "Do you want to update the system? (y/n/c): " displays a prompt without a newline at the end.
  • read -r response waits for the user to type a response (y, n, or c) and stores it in the variable response.
  • The case statement processes the response, determining what action to take based on the user's input.

As you can see, the read command makes your scripts interactive. You can get information from the user to customize how your script works. It's great for creating menus or asking for confirmation before doing something important.

Create Interactive Bash Scripts using Yes, No, and Cancel Operations

Here I have given three example scripts for making interactive scripts using read command and conditional statements.

Example 1: An Interactive Shell Script to Update a Debian-based System

Let's say you want to update your Debian Linux server. Before proceeding with the update, you want to prompt the user to confirm whether to continue, abort, or cancel the operation.

Here's an example Bash script for this task:

Explanation of the Script:

1. Prompt the User: The script prompts the user to confirm whether to update the software package.
2. Capture User Input: The read command captures the user's input.
3. Handle Input: The case statement processes the user's response, determining whether they selected Yes, No, or Cancel.
4. Update the Software:

  • If the user selects Yes ([Yy]*), the script proceeds with the software update using sudo apt-get update && sudo apt-get upgrade -y.
  • If the user selects No ([Nn]*), the script prints a message indicating that the update was aborted.
  • If the user selects Cancel ([Cc]*), the script prints a message indicating that the update was canceled.
  1. Invalid Input Handling: If the user inputs anything other than y, n, or c, the script prompts them again until they provide a valid response.

To use it, simply copy the above code in a text file, for example debupdate.sh. Make it executable:

chmod +x debupdate.sh

Run the script using command:

./debupdate.sh

Sample Output:

The script will only proceed to update the system if the user inputs y.

Do you want to update the software package? (y/n/c): y
You selected Yes.
Proceeding with the software update...
[sudo] password for ostechnix:
Hit:5 http://deb.debian.org/debian bullseye InRelease
Get:6 http://deb.debian.org/debian bullseye-updates InRelease [44.1 kB]
Get:7 http://deb.debian.org/debian bullseye-backports InRelease [49.0 kB]
Hit:9 http://security.debian.org/debian-security bullseye-security InRelease
Fetched 95.5 kB in 11s (8,768 B/s)
Reading package lists... Done
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Software update completed successfully.

This is just an example to illustrate the purpose of read command. It can be useful for users who need to ensure that updates are only applied with explicit confirmation.

Of course, you don't have to write a script for sudo apt-get update && sudo apt-get upgrade command. It is just an one-liner and you can run it on your Terminal without needing a script.

Example 2: Delete Old Log Files

Let's say you're a system administrator, and you need to write a script to remove old log files from a server. You want to make sure the user is aware of the consequences of running the script and give them a chance to cancel the operation.

Warning: DO NOT blindly run this script on your system. This script will delete files OLDER than 30 days from your /var/log/ directory. This is for demonstration purpose only. You must change the location of the directory before running it.

Here's an example script:

In this example, the script:

  1. Warns the user about the consequences of running the script.
  2. Asks the user to confirm whether they want to proceed.
  3. If the user enters 'y', the script removes all log files older than 30 days using the find command.
  4. If the user enters 'n', the script cancels the operation and displays a message.
  5. If the user enters 'c', the script exits without doing anything.
  6. If the user enters anything else, the script displays an error message and prompts the user again.

This script provides a safety net to prevent accidental deletion of important log files and gives the user a chance to reconsider their actions.

This script is not just for deleting old log files. You can use this script to find and delete files older than X days from any directory. Simply edit this script and change the location of the log directory to something else.

Example 3: Copy Files from One Directory to Another

Let's say you're writing a script to copy files from a source directory to a destination directory. You want to ask the user to confirm the operation before proceeding, especially if the destination directory already contains files with the same names.

Here's an example script:

Update the values of SOURCE_DIR and DEST_DIR in your script. Also, make sure the user has proper permission on the destination location.

In this example, the script:

  1. Informs the user about the operation and its potential consequences (overwriting files).
  2. Asks the user to confirm whether they want to proceed.
  3. If the user enters 'y', the script copies all files from the source directory to the destination directory using the cp command.
  4. If the user enters 'n', the script cancels the operation and displays a message.
  5. If the user enters 'c', the script exits without doing anything.
  6. If the user enters anything else, the script displays an error message and prompts the user again.

This script provides a safety net to prevent accidental overwriting of files and allows the user to reconsider their actions.

Conclusion

In this tutorial, we learned how to create interactive Bash shell scripts that ask the user Yes, No, or Cancel questions, and then use their response to make decisions.

For demonstration purposes, we used the read command to get user input, and then used if and case statements to evaluate the user's response and take the appropriate action.

This is not the only way to create interactive shell scripts in Linux, but it is one effective method. There are other ways as well, but I prefer using the read command for its simplicity.


Are you interested in Bash Scripting? We have published a bunch of Bash scripting tutorials for Beginners and Intermediate users. Check the following link to learn Bash scripting at your own convenience:


You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More