There are two main things we can use shell scripting for. The first is for scripts and second is for startup files.
Because the default login shell on the department machines is tcsh (a slightly more modern version of the C Shell), we will work with that. Most new systems use bash as their default shell, but due to our history as a mostly Sun setup, we still use tcsh. First we will work on stand alone scripts.
Shell scripts are plain text files. Simply make a file with your text
editor of choice. Make sure you have execute permissions on the file
(which will most likely not be set by default).
The first line of a shell script must be: #!/bin/tcsh
After that line, any line that starts with a # is a comment and
is ignored by the shell.
After the first line, you put commands (anything you would type at the
shell prompt), pipes and redirects, loops, and variables. The syntax
bears some relation to
the C language (hence the name "C-Shell"), but not much.
set variable = value
unset variable
set array = ( 1 2 3 )
echo $array[1] (note, arrays start at 1, not 0 like in C).
@var = $var1 + $var2
The last one shows that you need to use a $ when you use variables
except when you set or unset it. e.g., echo $var1
if ($array[1]>0)then
echo "true"
else
echo "false"
endif
foreach variable (list)
echo $variable
end
Most UNIX programs have options that are set by text files kept in
your home directory. These files are often called "dot-files" because
they begin with a period which makes them invisible. You can see them
by typing ls -a.
We will only take about the file to control your shell since it uses
the same syntax as shell scripts. For our shell (tcsh) the file is
either .cshrc or .tcshrc. Open this with your text editor and we can
see some of what we can do in this file.
The first thing is that after you change something in you .tcshrc
file, you must either open a new terminal, log out and back in, or
type source .tcshrc. Any of these things will make you changes
used by the shell you are working on.
The shell dot-file allows you to set environment variables. This is
done with:
setenv variable value
A common use for this is to add things to your path (where the shell
looks for programs to run).
setenv PATH /some/new/path:$PATH
You may also use the dot-file to setup aliases which are basically new
commands.
alias name 'command'
Note: Sometimes people try to make the rm command safer by doing
something like alias rm 'rm -i' so that rm asks for confirmation every
time you use it. This is a VERY BAD IDEA. Do not do this ever.
One last hint. If you go back and forth between the Linux machines
and the Suns, you may want to have parts of your dot-file only used on
one type of system. You may do this with if loops:
if ("$ARCH" == Linux) then (or sparcSolaris for the Suns)