leestretton.com

You are in: > Home > Developers Guides

Shell Scripting - Reading Variables From STDIN

To store a users input in a shell script use the 'read' command. This "Reads" the value of a variable from stdin, that is, it interactively fetches input from the keyboard.

An example of the use of read would is:

#!/bin/bash
 
echo
echo -n "What is your favorite vegetable? "
read

echo "Your favorite vegetable is $REPLY."
# REPLY holds the value of last "read" if and only if
# no variable supplied.

You will see that read stores it's result in a default variable called $REPLY. If you want to store the result in a variable with a name of your choice you simply add a variable name after the read command:

#!/bin/bash

echo
echo -n "What is your favorite fruit? "
read fruit
echo "Your favorite fruit is $fruit."
# the variable $fruit absorbed the new "read" value.

There are other options you can supply to the read command, for the entire list type 'man read' at a command prompt, here are the most common options:

SYNTAX
      read [-ers] [-a aname] [-p prompt] [-t timeout]
              [-n nchars] [-d delim] [name...]

OPTIONS

  -a aname 
    The words are assigned to sequential indices of the array variable aname, 
    starting at 0. All elements are removed from aname before the assignment. 
    Other name arguments are ignored.

  -d delim 
    The first character of delim is used to terminate the input line,
    rather than newline.

  -e 
    If the standard input is coming from a terminal, Readline is used
    to obtain the line.

  -n nchars
    read returns after reading nchars characters rather
    than waiting for a complete line of input.

  -p prompt
    Display prompt, without a trailing newline, before attempting
    to read any input. The prompt is displayed only if input is coming from a
    terminal.

  -r   
    If this option is given, backslash does not act as an escape character.
    The backslash is considered to be part of the line. In particular, a backslash-newline
    pair may not be used as a line continuation. 

  -s    
    Silent mode. If input is coming from a terminal, characters are not echoed.

  -t timeout   
    Cause read to time out and return failure if a complete line
    of input is not read within timeout seconds. This option has no
    effect if read is not reading input from the terminal or a pipe.

Problem with this page? Let us know
© Lee Stretton 2005 | powered by linux powered by php 5 powered by MySQL download rss feeds powered by php 5 valid css