start page | rating of books | rating of authors | reviews | copyrights

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 10.4 Aliases in ksh and bash Chapter 10
Aliases
Next: 10.6 Avoiding C Shell Alias Loops
 

10.5 Sourceable Scripts

A powerful concept in csh is that of aliases. Another great capability is shell scripts. Each has its strengths. An alias is just right for common sequences of commands, calling a command by a different name, and so on. Scripts are great for more flexible processing and batch processing. There are limitations to both, and I will show a way around them.

The limitation to aliases is that you are working pretty much with one command line. Consider this example:

alias pp 'set o2=$cwd; popd; set old=$o2; dir_number; record_dir pp; \\
  prompt_set; set cd_attempt=(\!*); if ($#cd_attempt > 0) cd $cd_attempt'

Now this works fine for me, and it served me well for a few years and thousands of invocations, but it's at the point where I start thinking that a script is more suited to the job. This brings me to the limitation of scripts...

Shell scripts are great for accomplishing some task that might change a file, start a program, etc. They are limited by the fact that any changes they make to shell or environment variables are not visible (38.3) to the parent shell that started them. In other words, you can write some really cool script that will change directories for you if you don't touch the keyboard for five seconds, but once the script exits, you are still in the same place you started.

The answer is to combine the best of both worlds. Consider this:

( ) 
alias pp 'set cd_attempt=(\!*); source ~/bin/pp_csh'

We set up a variable and source a script. The concept is this: put your command-line arguments into a variable and then source (44.23) a script in order to accomplish something. The difference here is that because you are not starting a subshell (38.4) for the script, it can do everything an alias can and more. This is much like Bourne shell functions (10.9).

Some hints on using this technique:

Have fun with this! You may find yourself tossing some old aliases and rewriting them as sourceable scripts. They're also easier to maintain.

- DS


Previous: 10.4 Aliases in ksh and bash UNIX Power ToolsNext: 10.6 Avoiding C Shell Alias Loops
10.4 Aliases in ksh and bash Book Index10.6 Avoiding C Shell Alias Loops

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System