Writing shell scripts

Besides interpreting commands typed in at the keyboard, the shell will also obey commands contained in a file. Such a file of commands is called a shell script.

  • Use a text editor to create a file containing the commands that you want the script to execute.

  • Make the file executable by changing the access permission with the command
    chmod u+x filename

Example

#!/bin/csh
# This script displays info about a file
# It accepts one parameter, the file name
ls -l $1
wc -l $1
file $1

If the above script were in a file called fi, then the command fi fred would print information about the file called fred.

  • The first line of the script must indicate which shell the file's contents should be interpreted by. #!/bin/csh indicates that the commands should be interpreted by the C shell.

  • The # character also marks the start of a comment. This can be on a line of its own or may follow the text of a command.

  • The first, second, ... ninth parameters to the script can be accessed using the notation $1, $2 ... $9.