Creating Variables in C Shell Scripts

Use set to set up your own shell variables.

#! /bin/csh
set a=hello
set b="hello world"
set c=(This variable has five elements)
echo $a
echo $b
echo $c

hello
hello world
This variable has five elements

a is a standard shell variable, b is a string variable. It is possible to determine the number of elements of a shell variable with the # operator.

echo $#b
1
echo $#c
5

To access the elements of an array variable, use $variable_name[element].

echo $c[3]
has

Accessing the Values of Shell Variables

The dollar sign placed in front of a shell variable allows access to the actual value of the variable, for example

#! /bin/csh
set message=hello
set message2="$message world"
echo $message2

hello world

Individual elements of a shell variable can also be accessed using the following:

Variable, Value(s)

$?name
0 if name not set, 1 if name set
#name
number of elements of name
$name[1-3]
first 3 elements of name
$name[2-]
elements 2 onwards of name
$name[*]
all elements of name
$name
all elements of name

Performing Arithmetical Operations on Shell Variables

Use the @ command, for example

#! /bin/csh
set i = 10
set j = 3
@ k = $i + $j
echo $k

13

#! /bin/csh
@ z = ($i / $j) * 2
echo $z

6

The space after the @ is vital, it separates the name of the command from its arguments. The arithmetic operators must have a space before and after them also.

Using Arguments with C Shell Scripts

Argument, Meaning

$0
name of script
$1
first argument to script
$2
second argument to script (and $3 for 3rd etc.)
$*
all arguments to script
$#argv
number of arguments to script
$argv[0]
name of script
$argv[1]
first argument to script
$argv[2]
second argument to script
$argv
all arguments to script
$$
current process number of shell
$<
read one line from standard input