Exporting shell functions into shell files

Rob Pike rob at alice.UucP
Wed Nov 20 14:37:54 AEST 1985


I will use two examples to explain why you want to export shell functions:
	hide() {
		for i in $*
		do
			eval $i'(){ echo "hidden '$i' $*" }' 
			export $i
		done
	}
hide takes a list of names and makes empty functions from them: functions
that just echo that they were called, but that do nothing.  (Note the pretty
indirection: this function makes more functions.)  This is useful
for debugging shell scripts and makefiles:
	% hide rm
	% rm foo
	hidden rm foo
	%
rm didn't really run, but you can see it would have.  So if "futz" is a shell
program you're working on that (once working) removes things, you can
debug futz without fear of losing precious files.  It's more useful that
these be functions than files because there is nothing to clean up later:
the functions go away when the shell you're working in disappears - when you
log off or delete the window.

A simpler example is that you can define a cc() function that sets an
extra argument so a makefile doesn't need to be examined or modified to
set CFLAGS.  Setting CFLAGS itself would work, but only if it is used
religiously in the makefile and if you know what value it has inside
(you can't add to it, only redefine it):
	% cc() /bin/cc -p $*
	% make a.out
will make a profiled version of a.out (assuming cc is called to compile it)
regardless of how the makefile is written.

The point about functions not being understood in csh files is valid, but
not interesting to me - my shell files are all sh files.


					Rob Pike



More information about the Comp.unix mailing list