Writing Your Own Shell Files

If you often invoke a command with certain options, or often do a series of commands, you may want to write a “shell file” that will do this without you having to type the commands each time. You can put such a shell files in a “bin” directory in your home directory. You will also need to tell the shell to look in this directory whenever you type a command by including it in the PATH variable in your .profile file (see setting Unix options in your .profile file).

Here’s an example. Suppose you often use the ls command with the -l option (which gives a long listing, with such information as file sizes). Rather than type this every time, you might want to write a shell file called ll that does this. First, you change into your bin directory, and use an editor to create a file called ll containing the single line

ls -l

Next, you need to inform Unix that this file can be executed as a command. You do this with the command

chmod +x ll

You can now use ll as a command by just typing it, achieving the same effect as typing ls -l. (If you are using the csh or tcsh shells, you will need to type the rehash command (just once) to get the shell to notice that there’s a new shell file.)

Shell files can get more sophisticated than this, as explained in various Unix books. One elaboration is that inside the shell file you can refer to “arguments” that were typed after its name, using the symbols “$1”, “$2”, etc. The whole list of arguments can be gotten as “$@”. Since ls can take arguments in addition to -l, you might want to allow for this by changing ll to contain the following:

ls -l $@

Now, for example, you could use the ll shell file to list only files beginning with the letter “a”, using the command:

ll a*

For more details, see one of the many books on Unix available in the U of T bookstore.

Print Friendly