How do you execute (run) a shell script?



Last revision August 6, 2004

There are two methods you can use to execute a shell script.

First, you can give the script file name as an argument to an instance of the shell program, that is, type a command like:
     csh filename
csh is the name of the C-shell program itself. This command starts up a new C-shell process that executes the commands in the script filename and then terminates.

Second, you can give the name of the shell script itself as a command, just like any other program on Unix. First, you have to let the Unix kernel recognize that this is a shell script by doing the following two steps. Then you can simply type the shell's filename as a command name to execute it. The kernel will automatically start up a new C-shell process to execute the commands in the script.

Note that your login shell has to be able to find the shell script file when you type its name as a command. The login shell only looks in a set of specific directories, called its path, to find files that contain programs. On pangea, the default path includes your current working directory, so you can run a shell script in the current directory simply by typing its name. Otherwise, type the absolute pathname of the script (for example, /home/sysop/farrell/programs/addup), or add the directory where the script lives to your standard path. Whenever you add a directory to your standard path, you must run the rehash built-in C-shell command to tell your login shell to rebuild its list of programs using your new path definition.

To make your shell script file executable as a program, do these steps:

Put the following line as the first line in your script:
     #! /bin/csh -f
This is a special comment telling the kernel that you want this script to be executed by the C-shell (there is an alternate shell named simply sh). The -f option helps the command to start up faster by skipping the initial read of the .cshrc file.

Use chmod to set execute permission for your file. For instance, if you want anyone to be able to execute the script file, use
     chmod ugo+x filename

Comments or Questions?