The following short example shows how read can be used to get input from the user:
#!/bin/sh
echo "Please enter your name:\c "
read NAME
echo your name is $NAME
exit 0
The
c means that the line feed will be suppressed, so that the
prompt sits at the end of the line, not at the beginning of the
following line.
Two more common controls available to the echo command are
to use
n to add a line feed, and
t to add a tab.
Multiple values may be read on a single line by using:
#!/bin/sh
echo "Please enter two numbers:\c "
read NUM1 NUM2
echo The numbers entered are $NUM1 and $NUM2
exit 0
This ensures that if two numbers are entered on a single line, they will
be read within two variables.
If three numbers were entered, the second variable (NUM2) would contain
the last two numbers.
Assuming three numbers were the input of the above example, the first two number could be the value of the first variable by entering them as
num1num2 num3
The backslash (
) allows the blank space between num1 and
num2 to be part of the variable (typically, spaces are use as
field separators.