How To Use The Read Command In Bash Scripts

Today I will be showing you how to use the read command as-well as some read command examples.

So what does the read command do? The read command allows you to do what the name might vaguely suggest, read user input and pass it to a variable. This can be useful for multiple reasons, whether you need to prompt a user for a specific value that will be used later in the script, as a yes or no prompt, or even as simple as a “press any key to continue prompt”.

Press Any Key To Continue Prompt

So lets get started with the easiest of all, prompting the user to press any key to continue executing our script. This will need two arguments, the -p to set our text and the -n to set the number of maximum characters as-well as automatically continue once that maximum is entered.

read -p "Press any key to continue..." -n 1

The command above will wait until the user enters 1 character and then automatically continue running the bash script.

Yes Or No Prompt

There are a couple ways you can accomplish this, first we will use the same command as above, then we will check the READ variable or whatever you set the variable name to and see what the response was. You can either use an if statement or a case statement. Using a case statement is better for this as we can easily accept multiple responses such as “Y, y, yes, YES, yea”. Here is an example of a yes/no prompt in a bash script, we will set the variable name to verify.

#!/bin/bash

read -p "Do you want to continue? (y/n): " verify

case "$verify" in
  y|Y|YES|yes)

    echo "Ok we will be continuing."
  ;;
  n|N|NO|no)
    echo "We will not continue."
    exit
  ;;

esac

Setting A Variable With The Read Command

You may someday need to be able to change a variable on the fly while running scripts, for example a script designed to connect to servers and automatically run specified commands (see my expect post for more info). You can use the read command to prompt the user for the desired hostname, even prompt the user for their password afterwards. I will give you a quick example of setting a variable and then using said variable below.

#!/bin/bash

read -p "Please enter your name: " name
echo "Pleased to meet you $name"

I hope you have enjoyed this post on using the read command, please don’t forget to like/comment/share. Thanks for the support!

 

Leave a Reply

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