User Input

Shell scripts are often interactive, requesting input in the form of data or parameters directly from the user via the keyboard. All shells have the ability to read input and assign it to shell variables.

In Bourne Shell derivatives, data can be input from the standard input using the read command:

#!/bin/sh -e

printf "Please enter the name of an animal: "
read animal
printf "Please enter an adjective: "
read adjective1
printf "Please enter an adjective: "
read adjective2
printf "The $adjective1 $adjective2 $animal jumped over the lazy dog.\n"
        

C shell and T shell use the special symbol $< rather than a command to read input:

#!/bin/csh -ef

printf "Please enter the name of an animal: "
set animal = "$<"
printf "Please enter an adjective: "
set adjective1 = "$<"
printf "Please enter an adjective: "
set adjective2 = "$<"
printf "The $adjective1 $adjective2 $animal jumped over the lazy dog.\n"
        

The $< symbol behaves like a variable, which makes it more flexible than the read command used by Bourne family shells. It can be used anywhere a regular variable can appear.

#!/bin/csh -ef

printf "Enter your name: "
printf "Hi, $<!\n"
        

Caution

The $< symbol should usually be enclosed in soft quotes in case the user enters text containing white space. Otherwise, only the first "word" of input (text before the first white space character) will be captured by a set command like those above.

Practice Break

Write a shell script that asks the user to enter their first name and last name, stores each in a separate shell variable, and outputs "Hello, first-name last-name". For example:

Please enter your first name: Barney
Please enter your last name: Miller
Hello, Barney Miller!
            
Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. Write a shell script that lists the files in the CWD, asks the user for the name of a file, a source string, and a replacement string, and then shows the file content with all occurrences of the source replaced by the replacement.

    shell-prompt: cat fox.txt
    The quick brown fox jumped over the lazy dog.
    
    shell-prompt: ./replace.sh
    Documents          R                  fox.txt            stringy
    Downloads          igv                stringy.c
    File name? fox.txt
    Source string? fox
    Replacement string? tortoise
    The quick brown tortoise jumped over the lazy dog.