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: 4) function
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
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/shhelp(){cat
shift by 2--) shift;break;; # end of options-*) echo "error: no such option $1. -h for help";exit 1;;*) break;;esacdoneecho "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:
cmdparser -l hello -f -- -somefile1 somefile2
The returned result is:
opt_f is 1opt_l is hellofirst arg is -somefile12nd 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.
The above is a detailed introduction to Linux shell script basics (6). For more information, see The PHP Chinese website (www.php1.cn )!