2.13. User Input

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

#!/usr/bin/env bash

printf "Please enter your name: "
read name
printf "Hello, $name!\n"
	

C shell and T-shell use a symbol rather than a command to read input:

#!/bin/csh

printf "Please enter your name: "
set name="$<"
printf "Hello, $name!\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

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

Note

The $< symbol should always be enclosed in soft quotes in case the user enters text containing white space.

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".

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

2.13.1. Self-test

  1. Do the practice break in this section if you haven't already.