Shell

Scripts

Multiple commands can be grouped in a shell script, which is treated like a single program. This allows for repeated processing of batch commands. To create a shell script follow these steps:

  1. edit <script>.sh with an editor (e.g. emacs)
  2. put “#!/bin/tcsh -f” as the first line
  3. the following lines of the script are executed as if typed on the console (with tcsh as shell)
  4. allow the script to be executed as an application: chmod +x <script>.sh

Then a simple tcsh shell script looks like that:

#!/bin/tcsh -f

# just output two lines of text
echo "Hi!"
echo "I am a shell script that will save you lots of time in the future!"

The arguments of a script when invoked from the command line have the shell variable names $1, $2, $3, … . So a typical tcsh shell script that expects a single command line argument looks like that:

#!/bin/tcsh -f

# check for single argument $1
if ($1 == "") then
   echo missing argument
   exit 1
endif

# do something meaningful with the single argument
# e.g. count the lines in a text file:
set filename=$1
echo the file $filename contains `wc -l $filename` lines of text

The error code of the last finished program is available via the variable $? . An error code of zero usually means that zero errors were encountered. Here is an example use case:

gcc program.c
if ($? > 0) then
   echo source file not found!
endif

With increasing programming experience the seasoned programmer will uncover the advantages of the shell and in particular the automation of repetitive and cumbersome tasks as a script.

Variables |

Options: