Functions
As in other languages, a function is a separate piece of code that performs some well-defined single task. The function can then be used (called) from multiple places within the larger program.
Functions must be defined before they can be used. This is done either at the beginning of a script, or by having them in a separate file and sourcing them with the "dot" (.) command. (The . command is discussed later on in Section 7.9.) They are defined as shown in Example 6-4.
Example 6-4. Wait for a user to log in, function version
# wait_for_user --- wait for a user to log in # # usage: wait_for_user user [ sleeptime ] wait_for_user ( ) { until who | grep "$1" > /dev/null do sleep ${2:-30} done }
Functions are invoked (executed) the same way a command is: by
providing its name and any corresponding arguments. The wait_for_user
function can be invoked in one
of two ways:
wait_for_user tolstoy Wait for tolstoy, check every 30 seconds wait_for_user tolstoy 60 Wait for tolstoy, check every 60 seconds
Within a function body, the positional parameters ($1
, $2
,
etc., $#
, $*
, and $@
)
refer to the function's arguments. The parent
script's arguments are temporarily shadowed, or
hidden, by the function's arguments. $0
remains the name of the parent script. When
the function finishes, the original command-line arguments are
restored.
Within a shell function, the return command serves the same function as exit and works the same way:
answer_the_question ( ) { ... return 42 }
Note that using ...
Get Classic Shell Scripting now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.