To define a function, you can use either one of two forms:
function functname{ shell commands}
or:
functname ( ) { shell commands}
You can also delete a function definition with the command unset -f functname.
You can find out what functions are defined in your login session by typing declare -f.
This is a good time to show the order of precedence for the various sources of com-
mands when you type a command to the shell:
1. Aliases
2. Keywords such as function and several others, like if and for, which we will see
in Chapter 5
3. Functions
4. Built-ins like cd and type
5. Scripts and executable programs, for which the shell searches in the directories
listed in the PATH environment variable
type has several options that allow you to find specific details of a command. If you want to find out all of the definitions for dodo you can use type -a. This will produce output similar to the following:
$ type -all dodo dodo is aliased to `echo "Everybody has won, and all must have prizes"' dodo is a function dodo ( ) { echo "Everybody has won, and all must have prizes" } dodo is ./dodo
It is also possible to restrict the search to commands that are executable files or shell
scripts by using the -p option. If the command as typed to bash executes a file or shell script, the path name of the file is returned; otherwise, nothing is printed. The -P option forces type to look for executable files or shell scripts even if the result of -t would not return file. A further option, -f, suppresses shell function lookup, i.e., only keywords, files and aliases will be returned. * The default output from type is verbose; it will give you the full definition for an alias
or function. By using the -t option, you can restrict this to a single word descriptor: alias, keyword, function, builtin, or file. For example:
$ type -t bash file $ type -t if keyword
The most important special, built-in variables are called positional parameters. These hold the command-line arguments to scripts when they are invoked. Positional parameters have the names 1, 2, 3, etc., meaning that their values are denoted by $1, $2, $3, etc. There is also a positional parameter 0, whose value is the name of the script (i.e., the command typed in to invoke it).
Two special variables contain all of the positional parameters (except positional parameter 0): * and @. The difference between them is subtle but important, and it’s apparent only when they are within double quotes.
“$*” is a single string that consists of all of the positional parameters, separated by the first character in the value of the environment variable IFS (internal field separator), which is a space, TAB, and NEWLINE by default. On the other hand, “$@” is equal to “$1” “$2”... “$N”, where N is the number of positional parameters. That is, it’s equal to N separate double-quoted strings, which are separated by spaces. If there are no positional parameters, “$@” expands to nothing. We’ll explore the ramifications of this difference in a little while.
-
$* 和 $@提供了对所有参数的快速访问
-
$* 会将所有参数当成单个参数
-
$@会单独处理每个参数
$cat test12 #!/bin/bash # testing $* and $@ count=1 for param in "$*" do echo "&* Parameter #$count = $param" count=$[ $count + 1 ] done count=1 for param in "$@" do echo "$@ Parameter #$count = $param" count=$[ $count+1 ] done $./test12 rich barbara katie jesica $* Parameter #1 = rich barbara katie jessica $@ Parameter #1= rich $@ Parameter #2=barbara $@ Parameter #3=katie $@ Parameter #4=jessica
Operator -------------
|
Substitution |
${varname:-word} |
If varname exists and isn’t null, return its value; otherwise return word.Purpose: Returning a default value if the variable is undefined.Example: ${count:-0} evaluates to 0 if count is undefined. |
${varname:=word} |
If varname exists and isn’t null, return its value; otherwise set it to word and then return its value. Positional and special parameters cannot be assigned this way.Purpose: Setting a variable to a default value if it is undefined.Example: ${count:=0} sets count to 0 if it is undefined. |
${varname:?message} |
If varname exists and isn’t null, return its value; otherwise print varname: followed by message, and abort the current command or script (non-interactive shells only). Omitting message produces the default message parameter null or not set.Purpose: Catching errors that result from variables being undefined.Example: {count:?“undefined!“} prints “count: undefined!” and exits if count is undefined. |
${varname:+word} |
If varname exists and isn’t null, return word; otherwise return null.Purpose: Testing for the existence of a variable.Example: ${count:+1} returns 1 (which could mean “true”) if count is defined. |
${varname:offset:length} |
Performs substring expansion. It returns the substring of $varname starting at offset and up to length characters. The first character in $varname is position 0. If length is omitted, the substring starts at offset and continues to the end of $varname. If offset is less than 0 then the position is taken from the end of $varname. If varname is @, the length is the number of positional parameters starting at parameter offset.Purpose: Returning parts of a string (substrings or slices).Example: If count is set to frogfootman, ${count:4} returns footman. ${count:4:4} returns foot. |
sort -nr $1 | head -${2:-10}
Here is how this works: the sort program sorts the data in the file whose name is given as the first argument ($1). The -n option tells sort to interpret the first word on each line as a number (instead of as a character string); the -r tells it to reverse the comparisons, so as to sort in descending order.
cor@debian:~/shell$ cat highest.sh
sort -nr $1|head -${2:-10}
cor@debian:~/shell$ . ./highest.sh myfile
sort: cannot read: myfile: No such file or directory
This is a perfectly good, runnable script—but it has a few problems. First, its one line is a bit cryptic. While this isn’t much of a problem for such a tiny script, it’s not wise to write long, elaborate scripts in this manner. A few minor changes will make the code more readable.
First, we can add comments to the code; anything between # and the end of a line is a comment. At a minimum, the script should start with a few comment lines that indicate what the script does and what arguments it accepts. Second, we can improve the variable names by assigning the values of the positional parameters to regular variables with mnemonic names. Finally, we can add blank lines to space things out; blank lines, like comments, are ignored. Here is a more readable version:
# # highest filename [howmany] # # Print howmany highest-numbered lines in file filename. # The input file is assumed to have lines that start with # numbers. Default for howmany is 10. # filename=$1 howmany=${2:-10} sort -nr $filename | head -$howmany