Shell Variables

Understanding Shell Variables

Like other programming languages the csh language has variables. Some variables are used to control the operation of the shell, such as $path and $history, which we discussed earlier. Other variables can be created and used to control the operation of a shell script file.

Setting Variables

Values of shell variable are all character-based: A value is formally defined to be a list of zero or more elements, and an element is formally defined to be a character string. In other words, a shell variable consists of an array of strings.

For example,

set  X

will set the variable $X to have an empty list as its value. The command

set  V  =  abc

will set V to have the string ‘abc’ as its value. The command

set  V  =  (123  def  ghi)

will set V to a list of three elements, which are the strings ‘123’, ‘def’ and ‘ghi’.

The several elements of a list can be treated like array elements. Thus for V in the last example above, $V[2] is the string ‘def’. We could change it, say to ‘abc’, by the command

set  V[2]  =  abc

Referencing and Testing Shell Variables

The value of a shell variable can be referenced by placing a $ before the name of the variable. The command

echo  $path

will output the value of the variable $path. Or you can access the variable by enclosing the variable name in curly brace characters, and then prefixing it with a $. The command

echo  ${path}

would have the same result as the last example. The second method is used when something is to be appended to the contents of the variable. For example, consider the commands

set fname = prog1 rm ${fname}.c

These would delete the file ‘prog1.c’.

To see how many elements are in a variable’s list, we prefix with a # then a $. The command

echo  $#V

above would print 3 to the screen, while

echo  $#path

would reveal the number of directories in your search path.

The @ command can be used for computations. For example, if you have shell variables $X and $Y, you can set a third variable $Z to their sum by

@Z  =  $X  +  $Y

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.