4) Functions
If you write a slightly more complex program, you will find that the same code may be used in several places in the program, and you will also find that if we use a function, it is much more convenient. A function looks like this:
Functionname ()
{
# Inside the body $1 is the first argument given to the Function
#$2 the second...
Body
}
You must declare the function at the beginning of each program.
The following is a script named xtitlebar. You can use this script to change the name of the terminal window.
Here we use a function called help. As you can see, this defined function is used twice.
#! /Bin/sh
# VIM: Set Sw = 4 ts = 4 et:
Help ()
{
Cat <
Xtitlebar -- change the name of an xterm, gnome-terminal or KDE konsole
Usage: xtitlebar [-H] "string_for_titelbar"
Options:-H help text
Example: xtitlebar "CVS"
Help
Exit 0
}
# In case of error or if-H is given we call the function help:
[-Z "$1"] & Help
["$1" = "-h"] & Help
# Send the escape sequence to change the xterm titelbar:
Echo-e "33] 0; $107"
#
It is a good programming habit to help other users (and you) use and understand scripts.
Command Line Parameters
We have seen Special variables such as $ * and $1, $2... $9. These special variables include the parameters you input from the command line. So far, we have only learned some simple command line syntax (such as some mandatory parameters and the-H option for viewing help ). However, when writing more complex programs, you may find that you need more custom options. The common practice is to add a minus sign before all optional parameters, followed by a parameter value (such as a file name ). There are many ways to analyze input parameters, but the following example using the case expression is a good method.
#! /Bin/sh
Help ()
{
Cat <
This is a generic command line parser demo.
Usage example: extends parser-l Hello-f ---somefile1 somefile2
Help
Exit 0
}
While [-n "$1"]; do
Case $1 in
-H) Help; shift 1; # function help is called
-F) opt_f = 1; shift 1; # variable opt_f is set
-L) opt_l = $2; Shift 2; #-l takes an argument-> shift by 2
--) Shift; break; # End of options
-*) Echo "error: no such option $1.-H for help"; Exit 1 ;;
*) Break ;;
Esac
Done
Echo "opt_f is $ opt_f"
Echo "opt_l is $ opt_l"
Echo "first Arg is $1"
Echo "2nd Arg is $2"
You can run the script as follows:
Extends parser-l Hello-f ---somefile1 somefile2
The returned result is:
Opt_f is 1
Opt_l is hello
First Arg is-somefile1
2nd Arg is somefile2
How does this script work? The script first loops through all input command line parameters and compares the input parameters with the case expression. If the input parameters match, a variable is set and the parameter is removed. According to the Convention of the UNIX system, the first input should be the parameter containing the minus sign.