home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Unix Power ToolsUnix Power ToolsSearch this book

29.12. Shell Function Specifics

Section 27.11 introduces shell functions for all Bourne-type shells. This article covers details of functions in specific shells.

Read-only functions
A bash and ksh function can be made read-only. In ksh, that means the function can't be changed. In bash, it can't be changed or removed. To make a function read-only, use the ksh command typeset -r funcname or use read-only -f funcname in bash, where funcname is the name of the function.

A system administrator might want to set read-only functions from a system-wide setup file (Section 3.3) like /etc/profile. bash users can't unset read-only functions, though. So once a function foo has been defined, how can you define your own foo? As Section 27.9 explains, you can type command foo to use a command named foo from your search path. Or define an alias named foo; aliases are used before functions. Finally, if you'd like to redefine the function, make an alias with the same name, then make the alias invoke a function with a (usually similar) name. For instance, to override a read-only function named foo:

alias foo=_foo
function _foo( ) {
    ...your foo function...
Changing function environment
If a function uses an environment variable -- like VISUAL or EDITOR (Section 35.5), your standard text editor -- you can set the value temporarily while the function executes. The syntax is the same for functions, but only in bash and zsh. For instance, if you usually use vi, but you want to use emacs as you run the work function (Section 29.11):

$ VISUAL=emacs work todo
Resetting zsh options
There are lots of zsh options. You may want to set some of them temporarily during a shell function without needing to reset them to their previous values when the function returns to the calling shell. To make that happen, set the LOCAL_OPTIONS option (run setopt local_options) in the function body.

For instance, maybe you use setopt nounset to make your interactive shell complain if you try to expand an unset shell variable. During your func function, though, you want to use the unset option to allow unset variables. Define the function like this:

function mullog( ) {
    setopt unset local_options
        ...do whatever...

-- JP and SJC

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.