Loading [MathJax]/jax/output/HTML-CSS/jax.js

7 Shell Variables

 7.1 Assigning scalar values
 7.2 Assigning arrays
 7.3 Using the values of variables
 7.4 Special characters
 7.5 Prompting
 7.6 Script arguments and other special variables
 7.7 Predefined variables

The shell lets you define variables to perform calculations, and to pass information between commands and applications. They are either integers or strings, however it is possible to perform floating-point arithmetic by using certain applications in your script (see Section 10.3). You don’t need to declare the data type explicitly; the type is determined when you assign a value to a variable.

Variables are only defined in the current process. If you want global variables, i.e. ones that are available to all processes, you should assign them in your .cshrc file.

Variable names comprise up to 20 letters, digits, and underscores; and should begin with a letter or underscore.

7.1 Assigning scalar values

You assign a value to a variable using the set command.

       set colour = blue
       set title = "Chiaroscuro 1997"
       set caption = "The most distant quasar observed is at redshift "
       set flux_100 = 1.2345E-09
       set n = 42
       set _90 = -1

The first four examples assign strings, and the last two assign integer values. Yes the value of flux_100 is not a real number. Multi-word strings should be enclosed in " quotes. The spaces around the equals sign are necessary.

You can also remove variables with the unset command. This accepts *?[ ]wildcards to match the names of the shell variables.

       unset colour
       unset iso_*             # iso_ followed by zero or more characters
       unset flux_1??          # flux_1 followed by any pair of characters
       unset [nx-z][0-9]*      # One of n, x, y, or z then an integer followed
                               # by zero or more characters

7.2 Assigning arrays

The set command is again used but the elements are space-separated lists enclosed by parentheses. Somewhat surprisingly for a shell that mimics C, array elements start at 1, like Fortran. Here are some illustrations.

       set colours = (blue yellow green red pink)
       set label = ("Count rate" Frequency "Integration time (sec)")
       set prime = (2 3 5 7 11 13 17 19 23)

The first element of colours is "blue", the second is "yellow" and so on. Multi-word elements must be in " quotes. So the first element of label is "Count rate", and the second is "Frequency". The seventh element of prime is 17.

7.3 Using the values of variables

To obtain the value of a variable, you prefix the variable’s name with the dollar sign.

       set count = 333
       echo Number of runs is $count

would write  Number of runs is 333  to standard output.

       set caption = "The most distant quasar observed is at redshift "
       set z = 5.1
       echo $caption$z

This will echo  The most distant quasar observed is at redshift 5.1.

       if ( $n > 10 ) then
          mem2d niter=$n out=deconv
          display style="’title=Result of deconvolution after $n iterations’" accept
       endif

This tests whether the value of variable n is greater than ten, and if it is, executes the statement within the if…endif structure. The value is also passed into an integer parameter of the application mem2d; and a string parameter of application display, so if n were forty, the resultant value would be "Result of deconvolution after 40 iterations".

Arithmetic, logical and string operations are presented in Sections 10 and 11.

The values of array elements are selected by appending the element index in brackets. This would echo to standard output the string  Starting search at co-ordinates x=300, y=256.

       set coords = (300 256)
       echo "Starting search at co-ordinates x=$coords[1], y=$coords[2]."

The following illustrates use of a text array to specify the annotations of a plot created with application linplot.

       set labels = ("Elapsed time" Flux "Light curve of 3C273")
       linplot style="’title=$labels[3],Label(1)=$labels[1],Label(2)=$labels[2]’"

There are some shorthands for specifying subsets of an array. The best way to describe them is through some examples. All the values assume set prime = (2 3 5 7 11 13 17 19 23).

Syntax

Meaning

Value



$#prime

Number of elements of variable prime

9
$prime[*]

All elements of variable prime

2 3 5 7 11 13 17 19 23
$prime[$]

The last element of variable prime

23
$prime[3-5]

The third to fifth elements of variable prime

5 7 11
$prime[8-]

The eighth to last elements of variable prime

21 23



Here we bring some of these ingredients together. Suppose we are experimenting trying to find the most suitable reddish background (palnum=0) colour for image display using the palentry command from Kappa. The script below loops using a while...end construct: all the commands inside the construct are repeated until the condition following the while is satisfied. That might seem a little odd here as we appear to repeat the same commands ad infinitum because the number of colours is fixed. That doesn’t happen because of the C-shell shift command. It discards the first element of an array and reduces the indices of the remaining elements by one, so the original $colours[2] becomes $colours[1] and so on. This means that the chosen background colour is always $colours[1]. The shift also decrements the number of colours by one. So the script changes the background colour and pauses for five seconds for you to consider the aesthetics.

       set colours = (red coral hotpink salmon brown sienna tan)
       while ( $#colours > 0 )
          echo "Trying $colours[1]"
          palentry palnum=0 colour=$colours[1]
          sleep 5
          shift colours
       end

7.4 Special characters

The shell has a number of special characters otherwise known as metacharacters. These include wildcard characters such as *?[ ], single and double quotes, parentheses, and the \ line continuation.

If you assign a value to a variable or application parameter which includes one or more of these metacharacters, you need to switch off the special meanings. This operation is called escaping. Single characters may be escaped with a backslash. For multiple occurrences single quotes ’ ’ will pass the enclosed text verbatim. Double quotes " " do the same as single quotes except that $, \, and left quote retain their special meaning.

       setlabel label=\"Syrtis Major\" \\
       set metacharacters = ’[]()/&><%$|#‘@’’"’
       stats europa’(200:299,~120)’
       stats europa"(200:299,~$y)"

In the first example the double quotes are part of parameter PLTITL (needed because of the embedded space) so are escaped individually. On its own \ means continue a line, but for Starlink tasks it is shorthand for the accept keyword. So we have to tell the shell to treat the backslash literally by preceding it with backslash!

In the last pair of examples an NDF section (see SUN/95’s chapter called “NDF Sections”) is specified. As the last contains a variable value to be substituted, the $ retains its normal special meaning but the parentheses are escaped by surrounding the section in double quotes.

7.5 Prompting

Some scripts might have parameters that cannot be defaulted, and so if their values are not given on the command line, the script needs to prompt for them.

       echo -n "Give the smoothing size"
       set size = $<

This will prompt for the parameter and store the entered value into shell variable size.

7.6 Script arguments and other special variables

The C-shell has some special forms of variable. We have seen some already: the $< for prompting, and how to specify array elements. The remainder largely concern command-line arguments. Here they are tabulated.

Syntax

Meaning



${0}

The name of the script being run

$?name

Returns 1 if the variable name is defined, or 0 if it is not defined

$n

The value of the nth argument passed to the script

$argv[n]

The value of the nth argument passed to the script

$#argv

The number of arguments passed to the script

$*

All the arguments supplied to the script

$$

Process identification number (useful for making temporary files with unique names)



Thus inside a script, any command-line arguments are accessed as shell variables $1, $2$#argv. There is no practical limit to the number of arguments you can supply.

Let’s look at a few examples. Below is a script argex.csh.

       #! /bin/csh
       echo ${0}
       echo "Number of arguments is $#argv"
       echo $2
       echo $argv[2-3]
       echo $argv[$]
       exit

Then we run it with four arguments.

       % argex.csh "hello world" 42 3.14159 "(300:400,~100)"
       argex.csh
       Number of arguments is 4
       42
       42 3.14159
       (300:400,~100)

Note that you must enclose any argument passed to a script that contains a space or shell metacharacter in double quotes (").

You can see an example using $* to process a list of files in Section 12.2.2. There are other examples of script arguments in Section 14.

7.7 Predefined variables

The C-shell has some predefined variables. We’ve already met argv. The most useful other ones are listed below.

Shell variable

Meaning



cwd

Current working directory

home

Home directory

path

List of directories in which to search for commands

status

The status returned by the last command, where 0 means a successful completion, and a positive integer indicates an error, the higher the value, the higher the severity.

user

Username



So if you wanted to include details of the user and directory at the head of some data-processing log you might write this in your script.

       % echo "Processed by:        $user" > logfile
       % echo "Directory processed: $path" >> logfile

This writes a heading into file logfile saying who ran the script, and then appends details of the directory in which processing occurred. Note the different metacharacters, namely > redirects the output to a file, and » appends to an existing file.