Linux Know-How provides a collection of introductory texts on often needed Linux skills. |
Home Bash Guide for Beginners Functions Examples of functions in scripts | ||||
See also: Introduction to Functions | ||||
Search the VIAS Library | Index | ||||
Examples of functions in scriptsRecyclingThere are plenty of scripts on your system that use functions as a structured way of handling series of commands. On some Linux systems, for instance, you will find the /etc/rc.d/init.d/functions definition file, which is sourced in all init scripts. Using this method, common tasks such as checking if a process runs, starting or stopping a daemon and so on, only have to be written once, in a general way. If the same task is needed again, the code is recycled. From this functions file the checkpid function:
This function is reused in the same script in other functions, which are reused in other scripts. The daemon function, for instance, is used in the majority of the startup scripts for starting a server process (on machines that use this system). Setting the pathThis section might be found in your /etc/profile file. The function pathmunge is defined and then used to set the path for the root and other users:
The function takes its first argument to be a path name. If this path name is not yet in the current path, it is added. The second argument to the function defines if the path will be added in front or after the current PATH definition. Normal users only get /usr/X11R6/bin added to their paths, while root gets a couple of extra directories containing system commands. After being used, the function is unset so that it is not retained. Remote backupsThe following example is one that I use for making backups of the files for my books. It uses SSH keys for enabling the remote connection. Two functions are defined, buplinux and bupbash, that each make a .tar file, which is then compressed and sent to a remote server. After that, the local copy is cleaned up. On Sunday, only bupbash is executed.
This script runs from cron, meaning without user interaction, so we redirect standard error from the scp command to /dev/null. It might be argued that all the separate steps can be combined in a command such as tar c dir_to_backup/ | bzip2 | ssh server "cat > backup.tar.bz2" However, if you are interested in intermediate results, which might be recovered upon failure of the script, this is not what you want. The expression command &> file is equivalent to command > file 2>&1
|
||||
Home Bash Guide for Beginners Functions Examples of functions in scripts |