SHELL VARIABLES:
* The first useful command to know about in building shell programs is "echo", which can be used to produce output from a shell program:
echo "This is a test!"
This sends the string "This is a test!" to standard output. It is recommended to write shell programs that generate some output to inform the user of what they are doing.
The shell allows variables to be defined to store values. It's simple, just declare a variable is assign a value to it:
shvar="This is a test!"
The string is enclosed in double-quotes to ensure that the variable swallows the entire string (more on this later), and there are no spaces around the "=". The value of the shell variable can be obtained by preceding it with a "$":
echo $shvar
This displays "This is a test!". If no value had been stored in that shell variable, the result would have simply been a blank line. Values stored in shell variables can be used as parameters to other programs as well:
ls $lastdir
The value stored in a shell variable can be erased by assigning the "null string" to the variable:
shvar=""
There are some subtleties in using shell variables. For example, suppose a shell program performed the assignment:
allfiles=*
-- and then performed:
echo $allfiles
This would echo a list of all the files in the directory. However, only the string "*" would be stored in "allfiles". The expansion of "*" only occurs when the "echo" command is executed.
Another subtlety is in modifying the values of shell variables. Suppose we have a file name in a shell variable named "myfile" and want to copy that file to another with the same name, but with "2" tacked on to the end. We might think to try:
mv $myfile $myfile2
-- but the problem is that the shell will think that "myfile2" is a different shell variable, and this won't work. Fortunately, there is a way around this; the change can be made as follows:
mv $myfile ${myfile}2
A UNIX installation will have some variables installed by default, most importantly $HOME, which gives the location of a particular user's home directory.
As a final comment on shell variables, if one shell program calls another and the two shell programs have the same variable names, the two sets of variables will be treated as entirely different variables. To call other shell programs from a shell program and have them use the same shell variables as the calling program requires use of the "export" command:
shvar="This is a test!" export shvar echo "Calling program two." shpgm2 echo "Done!"
If "shpgm2" simply contains:
echo $shvar
-- then it will echo "This is a test!".
0 comments:
Post a Comment