04. Reading user input read

To read user input into your shell program using standard in, simply use the read command.

printf 'How are you doing today? '
read user_input

The following will output the question "How are you doing today?" and allow the user to input some string.

Multiple values at once

You may use the read command to read in multiple values at once, separated by a space.

printf 'Enter your last name, first name, and position: '
read last_name first_name position
printf 'Your last name entered is %s. \n' $last_name
printf 'Your first name entered is %s. \n' $first_name
printf 'Your position is %s. \n' $position

Hinting what the user has to input

We may hint at what info the user has to give by using the -p option.

printf 'What are your first and last names? '
read -p "First name: " first_name
read -p "Last name: " last_name

This will output "First name: " on the command prompt, notifying the user that he or she needs to type out his first name.

Sample script

Let's try a sample script named name that reads in a user's first name and last name, then outputs it back.

printf "Hello, welcome!\n"
printf "What is your name? \n"
read -p "First Name: " first_name
read -p "Last Name: " last_name
printf "Oh, okay %s %s. \nWelcome to the command line!" $first_name $last_name

Here's what it looks like in action:

$ ./name
Hello, welcome! What is your name? First Name: Ted Last Name: Bundy Oh, okay Ted Bundy. Welcome to the command line!

Reading in passwords

When a user inputs a password, we want to avoid having those characters echoed out. We can do this by turning off echo with stty.

printf "Enter a new password: "
stty -echo  # Turns off echoing characters
read pass1
printf "\nPlease enter again: "
read pass2
stty echo   # Turn echoing feature back on
printf "\nYou entered two passwords: %s and %s.\n" pass1 pass2

Take your Linux skills to the next level!

Command Line Kung Fu

Take your Linux skills to the next level! Try Linux & UNIX

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources