Creating Functions


In ksh and bash, you can create your own functions. Functions can be used within a script to break up large sections of code, or to make it easy to reuse a block of code. For example,

 function factorial {     n=$1     FACT=1     while [ $n -gt 0]     do         FACT='expr $FACT \* $n'         n='expr $n − 1'     done     echo "$1 factorial is $FACT" } for NUM in $* do     factorial $NUM done

The arguments to a function are saved in the positional parameters $1, $2, and so on. These values only apply within the function-when execution returns to the main body of code, the positional parameters still have their earlier values.

You can also use functions to define more advanced aliases in your configuration files. For example, you could add these lines to your .bashrc or .kshrc file to define a command called del. The del command will move files to a hidden “wastebasket” directory instead of deleting them.

 function del{     mv $* $HOME/.Wastebasket }




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net