6.1 Shell Variables


5. Shell Variables: A facility for storing information in the running
shell's memory.
   Definition phase: $ var=value
   Evaluation phase: $ echo $var ${var}
   Lifetime (Scope): For the current shell or program only
   Extended Scope:   $ export var     # extends to all subsequent subprocesses
   Legal characters for variable names: 1st character: letter or underscore
				other characters: letter, digit, underscore

   In a shell script, you can ask for information while the script is running
using the read command. The read command is your input mechanism. It takes
at least one argument which is a shell variable name (without the $ since it
is being defined by the keyboard input.).  When the read command is run
in your script, the script pauses to acquire the keyboard input. However, if
the user doesn't know what to do, there will be a waiting contest (which the
script will win). Use the echo command before the read command to instruct
the user of your script to type the required information.

6. Examples:

$ x=sort
$ echo $x1

$ echo ${x}1
sort1
$ count=10
$ echo "The countdown starts at $count"
The countdown starts at 10
$ w="Earth#ling"
$ echo $w
Earth#ling
$ echo Earth #ling
Earth
$ cat dialog
echo "Please type in your favorite word and number: \c"
read line
echo "you typed $line"
$ sh dialog
Please type in your favorite word and number: more 5
you typed more 5
$

7. Parameters to Scripts: $n  nth parameter or argument (1<=n<=9)
			  $0  the name of the script
 			  $#  The total number of parameters
			  $*  The entire parameter list starting with $1
			  $@  The entire parameter list starting with "$1"
			  $$  The process id (PID) of the current shell
			  $?  The exit status of the last command (0 means
			        successful [true], non-zero means 
			        unsuccessful [false])

8. More Examples

$ who > /tmp/temp$$
$ ls /tmp/temp$$
/tmp/temp12345
$ rm /tmp/temp$$
$ ls /tmp/temp12345
ls: /tmp/temp12345 not found

$ cat datescript
date
$ cat helloscript
echo hello
$ cat betterscript
echo $1
$ sh datescript
$ chmod a+x datescript
$ datescript
$ ./datescript
$ sh < datescript
$ sh helloscript
$ sh helloscript things
$ sh betterscript stuff
$ sh betterscript more stuff

Questions? Robert Katz: rkatz@ned.highline.edu
Last Update July 30, 2002