29.7. Sourceable ScriptsAliases are a powerful concept in csh. Another great capability is shell scripts (Section 1.8). 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, which manages various stages of changing directories, updating the prompt, and so forth: 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 (Section 24.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 (Section 35.29) a script to accomplish something. The difference here is that because you are not starting a subshell (Section 24.4) for the script, it can do everything an alias can and more. This is much like Bourne shell functions (Section 29.11). 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 Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|