Previous Section  < Day Day Up >  Next Section

10.2. Reading User Input

10.2.1 The $< Variable

To make a script interactive, a special C shell variable is used to read standard input into a variable. The $< symbol reads a line from standard input up to but not including the newline, and assigns the line to a variable.[1]

[1] Another way to read one line of input is setvariable = 'head -1'.

Example 10.3.

(The Script - greeting)

    #/bin/csh -f

    # The greeting script

1   echo -n  "What is your name? "

2   set name = $<

3   echo Greetings to you, $name.



(The Command Line)

    % chmod +x greeting

    % greeting

1   What is your name?  Dan Savage

3   Greetings to you, Dan Savage.


EXPLANATION

  1. The string is echoed to the screen. The –n option causes the echo command to suppress the newline at the end of the string. On some versions of echo, use a \c at the end of the string to suppress the newline; for example, echo hello\c.

  2. Whatever is typed at the terminal, up to a newline, is stored as a string in the name variable.

  3. The string is printed after variable substitution is performed.

10.2.2 Creating a Wordlist from the Input String

Because the input from the $< variable is stored as a string, you may want to break the string into a wordlist.

Example 10.4.

1   % echo What is your full name\?

2   % set name = $<

    Lola Justin Lue

3   % echo Hi $name[1]

    Hi Lola Justin Lue

4   % echo $name[2]

    Subscript out of range.

5   % set name = ( $name )

6   % echo Hi $name[1]

    Hi Lola

7   % echo $name[2] $name[3]

    Justin Lue


EXPLANATION

1. The user is asked for input.

2. The special variable $< accepts input from the user in a string format.

3. Because the value Lola Justin Lue is stored as a single string, the subscript [1] displays the whole string. Subscripts start at 1.

4. The string consists of one word. There are not two words, so by using a subscript of [2], the shell complains Subscript out of range.

5. To create a wordlist, the string is enclosed in parentheses. An array is created. The string is broken up into a list of words and assigned to the variable name.

6. The first element of the array is printed.

7. The second and third elements of the array are printed.

    Previous Section  < Day Day Up >  Next Section