Appendix B. 参考卡片
下面的参考卡片提供了对于某些特定的脚本概念的一个总结. 之前我们已经对这里所提及的概念进行了详细的解释, 并且给出了使用的例子.
表格 B-1. 特殊的shell变量
变量 | 含义 |
---|---|
$0 | 脚本名字 |
$1 | 位置参数 #1 |
$2 - $9 | 位置参数 #2 - #9 |
${10} | 位置参数 #10 |
$# | 位置参数的个数 |
"$*" | 所有的位置参数(作为单个字符串) * |
"$@" | 所有的位置参数(每个都作为独立的字符串) |
${#*} | 传递到脚本中的命令行参数的个数 |
${#@} | 传递到脚本中的命令行参数的个数 |
$? | 返回值 |
$$ | 脚本的进程ID(PID) |
$- | 传递到脚本中的标志(使用set) |
$_ | 之前命令的最后一个参数 |
$! | 运行在后台的最后一个作业的进程ID(PID) |
* 必须被引用起来, 否则默认为"$@
".
表格 B-2. 测试操作: 二元比较
操 作 | 描述 | ----- | 操作 | 描述 |
---|---|---|---|---|
算 术比较 | 字符串比较 | |||
-eq | 等于 | = | 等于 | |
== | 等于 | |||
-ne | 不等于 | != | 不等于 | |
-lt | 小于 | \< | 小于 (ASCII) * | |
-le | 小于等于 | |||
-gt | 大于 | \> | 大于 (ASCII) * | |
-ge | 大于等于 | |||
-z | 字符串为空 | |||
-n | 字符串不为空 | |||
算 术比较 | 双括号(( ... ))结构 | |||
> | 大于 | |||
>= | 大于等于 | |||
< | 小于 | |||
<= | 小于等于 |
* 如果在双中括号 [[ ... ]] 测试结构中使用的话, 那么就不需要使用转义符\了.
表格 B-3. 文件类型的测试操作
操作 | 测 试条件 | ----- | 操作 | 测试条件 |
---|---|---|---|---|
-e | 文件是否存在 | -s | 文件大小不为0 | |
-f | 是一个标准文件 | |||
-d | 是一个目录 | -r | 文件具有读权限 | |
-h | 文件是一个符号链接 | -w | 文件具有写权限 | |
-L | 文件是一个符号链接 | -x | 文件具有执行权限 | |
-b | 文件是一个块设备 | |||
-c | 文件是一个字符设备 | -g | 设置了sgid标记 | |
-p | 文件是一个管道 | -u | 设置了suid标记 | |
-S | 文件是一个socket | -k | 设置了"粘贴位" | |
-t | 文件与一个终端相关联 | |||
-N | 从这个文件最后一次被读取之后, 它被修改过 | F1 -nt F2 | 文件F1比文件F2新 * | |
-O | 这个文件的宿主是你 | F1 -ot F2 | 文件F1比文件F2旧 * | |
-G | 文件的组id与你所属的组相同 | F1 -ef F2 | 文件F1和文件F2都是同一个文件的硬链接 * | |
! | "非" (反转上边的测试结果) |
* 二元操作符(需要两个操作数).
表格 B-4. 参数替换和扩展
表达式 | 含义 |
---|---|
${var} | 变量var 的 值, 与$var 相同 |
${var-DEFAULT} | 如果var 没 有被声明, 那么就以$DEFAULT 作为其值 * |
${var:-DEFAULT} | 如果var 没 有被声明, 或者其值为空, 那么就以$DEFAULT 作为其值 * |
${var=DEFAULT} | 如果var 没 有被声明, 那么就以$DEFAULT 作为其值 * |
${var:=DEFAULT} | 如果var 没 有被声明, 或者其值为空, 那么就以$DEFAULT 作为其值 * |
${var+OTHER} | 如果var 声 明了, 那么其值就是$OTHER , 否则就为null字符串 |
${var:+OTHER} | 如 果var 被设置了, 那么其值就是$OTHER , 否则就为null字符串 |
${var?ERR_MSG} | 如果var 没 被声明, 那么就打印$ERR_MSG * |
${var:?ERR_MSG} | 如果var 没 被设置, 那么就打印$ERR_MSG * |
${!varprefix*} | 匹配之前所有以varprefix 开头进行声明的变量 |
${!varprefix@} | 匹配之前所有以varprefix 开头进行声明的变量 |
* 当然, 如果变量var
已经被设置的 话, 那么其值就是$var
.
表格 B-5. 字符串操作
表达式 | 含义 |
---|---|
${#string} | $string 的 长度 |
${string:position} | 在$string 中, 从位置$position 开始提取子串 |
${string:position:length} | 在$string 中, 从位置$position 开始提取长度为$length 的子串 |
${string#substring} | 从 变量$string 的开头, 删除最短匹配$substring 的子串 |
${string##substring} | 从 变量$string 的开头, 删除最长匹配$substring 的子串 |
${string%substring} | 从 变量$string 的结尾, 删除最短匹配$substring 的子串 |
${string%%substring} | 从 变量$string 的结尾, 删除最长匹配$substring 的子串 |
${string/substring/replacement} | 使用$replacement , 来代替第一个匹配的$substring |
${string//substring/replacement} | 使 用$replacement , 代替所有匹配的$substring |
${string/#substring/replacement} | 如 果$string 的前缀匹配$substring , 那么就用$replacement 来代替匹配到的$substring |
${string/%substring/replacement} | 如果$string 的后缀匹配$substring , 那么就用$replacement 来代替匹配到的$substring |
expr match "$string" '$substring' | 匹配$string 开头的$substring * 的长度 |
expr "$string" : '$substring' | 匹 配$string 开头的$substring * 的长度 |
expr index "$string" $substring | 在$string 中匹配到的$substring 的第一个字符出现的位置 |
expr substr $string $position $length | 在$string 中 从位置$position 开始提取长度为$length 的子串 |
expr match "$string" '\($substring\)' | 从$string 的 开头位置提取$substring * |
expr "$string" : '\($substring\)' | 从$string 的 开头位置提取$substring * |
expr match "$string" '.*\($substring\)' | 从$string 的 结尾提取$substring * |
expr "$string" : '.*\($substring\)' | 从$string 的 结尾提取$substring * |
* $substring
是一个正 则表达式.
表格 B-6. 一些结构的汇总
表 达式 | 解释 |
---|---|
中 括号 | |
if [ CONDITION ] | 测 试结构 |
if [[ CONDITION ]] | 扩 展的测试结构 |
Array[1]=element1 | 数 组初始化 |
[a-z] | 正 则表达式的字符范围 |
大括号 | |
${variable} | 参数替换 |
${!variable} | 间 接变量引用 |
{ command1; command2; . . . commandN; } | 代码块 |
{string1,string2,string3,...} | 大 括号扩展 |
圆 括号 | |
( command1; command2 ) | 子shell中 执行的命令组 |
Array=(element1 element2 element3) | 数组初始化 |
result=$(COMMAND) | 在 子shell中执行命令, 并将结果赋值给变量 |
>(COMMAND) | 进 程替换 |
<(COMMAND) | 进 程替换 |
双圆括号 | |
(( var = 78 )) | 整型运算 |
var=$(( 20 + 5 )) | 整型运算, 并将结果赋值给变量 |
引 号 | |
"$variable" | " 弱"引用 |
'string' | "强"引用 |
后 置引用 | |
result=`COMMAND` | 在 子shell中运行命令, 并将结果赋值给变量 |
START_TIME=`date +%s`系统开机到现在经过的秒数
local passed_secs=$((`date +%s` - $START_TIME))
其 实可以直接使用 $SECONDS
--------------------------------
shell 的function返回数值,比如
function test_func() {
return 255 # return 256
}
如果return 255,那么echo $?等于255
如果return 256,那么echo $?等于0
所 以$?只占一个字节的空间,函数返回数据最大不能超过255,
而且函数只能返回整数,不能返回字符串
--------------------------------
如 果$2参数没有输入,那么设置SECONDS默认5秒
[ -z $2 ] && SECONDS=5
--------------------------------
查 询输入的参数为0-9的数字字符串
echo "$2" | grep -q '[^0-9]' && Usage && exit 1
--------------------------------
$RANDOM: 产生随机整数
$RANDOM 是Bash的内部函数 (并不是常量), 这个函数将返回一个伪随机 [1] 整数, 范围在0 - 32767之间. 它不应该被用来产生密匙.
我 们可以重新分配随机数种子:
RANDOM=1 赋值操作就是产生一个新的随机数种子.
RANDOM=$$ 当前脚本进程ID作为随机数种子
break命令可以带一个参数. 一个不带参数的break命令只能退出最内层的循环, 而break N可以退出N层循环.
continue N结构如果用在有意义的场合中, 往往都很难理解, 并且技巧性很高. 所以最好的方法就是尽量避免使用它.《摘自:http://www.tsnc.edu.cn/default/tsnc_wgrj/doc/abs- 3.9.1_cn/html/loopcontrol.html》
{if ($1 == "'"$module"'") n = "yes";}
"'"表示输入一个'单引号
所以分解为
"'"
$module
"'"
exec 9<&0 <struct.c ; while read line; do echo 'luther.gliethttp '$line; done ; exec 0<&- 0<&9
while read line; do echo 'luther.gliethttp '$line; done <struct.c
--------------------------------
1. 遍历~/目录下的所有文件夹和文件
for FILE in ~/* ; do echo $FILE ; done
所有隐藏文件和目录
for FILE in ~/.* ; do echo $FILE ; done
luther@gliethttp:~$ for FILE in ~/run.sh/* ; do echo $FILE ; done
/home/luther/run.sh/*
如果对文件执 行操作,那么将直接返回/home/luther/run.sh/*
luther@gliethttp:~$ for FILE in ~/run.sh/.* ; do echo $FILE ; done
/home/luther/run.sh/.*
case "aaa" in "ac") echo 'aaaa' ;; "ac") echo 'ccc' ;; *) echo 'bbb' ;; esac
case可以有相同的数据,但是将只是匹配第一个出现的case数据值下的内容.
*)类似于default:关键字
'$1/*' | '$1/.' | '$1/..')这里|表示或
is_empty_dir() {
for FILE in $1/* $1/.*
do
case "$FILE" in
"$1/.*") return 0 ;;
"$1/*"|"$1/."|"$1/..") continue ;;
*) return 1 ;;
esac
done
return 0
}
--------------------------------
exec < infile 默认赋值给lib库中的文件描述符0
exec > outfile 默认从lib库中的文件描述符1输出
exec > outfile 2> errfile 将2描述符erro信息输出到文件errfile
exec 3<struct.c ; cat <&3
$ read line1 < names; echo $line1; read line2 < names; echo $line2
Alice Jones
Alice Jones
$ (read line1; echo $line1; read line2; echo $line2) < names
Alice Jones
Robert Smith
$ exec 3< names
$ read -u3 line1; echo $line1; read -u3 line2; echo $line2
Alice Jones
Robert Smith
$ exec 3<&-
$ to_screen1 > out 2> err
message to the user
$ cat out
message to standard output
$ cat err
luther@gliethttp:~$ exec 9<&0 <struct.c ; read tab1 tab2 tab3 ; echo $tab1 ; echo $tab2 ; echo $tab3 ; read line ; echo $line ; exec 0<&- 0<&9
Help
on
module struct:
NAME
luther@gliethttp:~$ cat struct.c
Help on module struct:
NAME
struct
FILE
/usr/lib/python2.5/struct.py
MODULE DOCS
http://www.python.org/doc/current/lib/module-struct.html
所以read可以根据 tab,空格等来进一步细分,读取一行中的某几个域,这在ubuntu7.10的/lib/init/mount-functions.sh是一个很好的 学习范例.
--------------------------------
if [ -f /etc/fstab ]
then
exec 9<&0 </etc/fstab
while read TAB_DEV TAB_MTPT TAB_FSTYPE TAB_OPTS TAB_REST
do
case "$TAB_DEV" in (""|\#*) continue ;; esac
[ "$MTPT" = "$TAB_MTPT" ] || continue
[ "$FSTYPE" = "$TAB_FSTYPE" ] || continue
case "$TAB_OPTS" in
noauto|*,noauto|noauto,*|*,noauto,*)
exec 0<&9 9<&-
return
;;
?*)
OPTS="-o$TAB_OPTS"
;;
esac
break
done
exec 0<&9 9<&-
fi
case "$TAB_DEV" in (""|\#*) continue ;; esac
""表示空行,如果改行只有一个回车或者tab空格等,字符串将等于空""
|表示或
\#*表示 以#号开头的内容
\#表示符号#
*表示所有字符
noauto|*,noauto|noauto,*|*,noauto,*)
分 为几段:
noauto或者*,noauto或者noauto,*或者*,noauto,*都可以使case "$TAB_OPTS" in 成立
?*) 表示至少有1个字符,?表示一个字符
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
摘 自:http://www.chinaitpower.com/2005September/2005-09-13/204656.html
K shell program guide(1)
1)
Wildcard | Matches |
---|---|
? | Any single character |
* | Any string of characters |
[set] | Any character in set |
[!set] | Any character not in set |
Expression | Matches |
---|---|
[abc] | a, b, or c |
[.,;] | Period, comma, or semicolon |
[-_] | Dash and underscore |
[a-c] | a, b, or c |
[a-z] | All lowercase letters |
[!0-9] | All non-digits |
[0-9!] | All digits and exclamation point |
[a-zA-Z] | All lower- and uppercase letters |
[a-zA-Z0-9_-] | All letters, all digits, underscore, and dash |
Utility | Purpose |
---|---|
cat | Copy input to output |
grep | Search for strings in the input |
sort | Sort lines in the input |
cut | Extract columns from input |
sed | Perform editing operations on input |
tr | Translate characters in the input to other characters |
fc -l
fc -e - number
5)
user's environment file is .profile.
6)Built-in Commands and Keywords
Here is a summary of all built-in commands and keywords.
Command | Chapter | Summary |
---|---|---|
: | 7 | Do nothing (just do expansions of arguments). |
. | 4 | Read file and execute its contents in current shell. |
alias | 3 | Set up shorthand for command or command line. |
bg | 8 | Put job in background. |
break | 5 | Exit from surrounding for, select, while, or until loop. |
case | 5 | Multi-way conditional construct. |
cd | 1 | Change working directory. |
continue | Skip to next iteration of for, select, while, or until loop. | |
echo | 4 | Expand and print arguments (obsolete). |
exec | 9 | Replace shell with given program. |
exit | 5 | Exit from shell. |
export | 3 | Create environment variables. |
eval | 7 | Process arguments as a command line. |
fc | 2 | Fix command (edit history file). |
fg | 8 | Put background job in foreground. |
for | 5 | Looping construct. |
function | 4 | Define function. |
getopts | 6 | Process command-line options. |
if | 5 | Conditional construct. |
jobs | 1 | List background jobs. |
kill | 8 | Send signal to process. |
let | 6 | Arithmetic variable assignment. |
newgrp | Start new shell with new group ID. | |
1 | Expand and print arguments on standard output. | |
pwd | 1 | Print working directory. |
read | 7 | Read a line from standard input. |
readonly | 6 | Make variables read-only (unassignable). |
return | 5 | Return from surrounding function or script. |
select | 5 | Menu generation construct. |
set | 3 | Set options. |
shift | 6 | Shift command-line arguments. |
time | Run command and print execution times. | |
trap | 8 | Set up signal-catching routine. |
typeset | 6 | Set special characteristics of variables. |
ulimit | 10 | Set/show process resource limits. |
umask | 10 | Set/show file permission mask. |
unalias | 3 | Remove alias definitions. |
unset | 3 | Remove definitions of variables or functions. |
until | 5 | Looping construct. |
wait | 8 | Wait for background job(s) to finish. |
whence | 3 | Identify source of command. |
while | 5 | Looping construct. |
Built-in Shell Variables
Variable | Chapter | Meaning |
---|---|---|
# | 4 | Number of arguments given to current process. |
- | Options given to shell on invocation. | |
? | 5 | Exit status of previous command. |
$ | 8 | Process ID of shell process. |
_ | Last argument to previous command. | |
! | 8 | Process ID of last background command. |
CDPATH | 3 | List of directories for cd command to search. |
COLUMNS | 3 | Width of display in columns (for editing modes and select). |
EDITOR | 2 | Used to set editing mode; also used by mail and other programs. |
ERRNO | A | Error number of last system call that failed. |
ENV | 3 | Name of file to run as environment file when shell is invoked. |
FCEDIT | 2 | Default editor for fc command. |
FPATH | 4 | Search path for autoloaded functions. |
IFS | 7 | Internal field separator: list of characters that act as word separators. Normally set to SPACE, TAB, and NEWLINE. |
HISTFILE | 2 | Name of command history file. |
HISTSIZE | 2 | Number of lines kept in history file. |
HOME | 3 | Home (login) directory. |
LINENO | 9 | Number of line in script or function that just ran. |
LINES | 3 | Height of display in lines (for select command). |
3 | Name of file to check for new mail. | |
MAILCHECK | 3 | How often (in seconds) to check for new mail. |
MAILPATH | 3 | List of file names to check for new mail, if MAIL is not set. |
OLDPWD | 3 | Previous working directory. |
OPTARG | 6 | Argument to option being processed by getopts. |
OPTIND | 6 | Number of first argument after options. |
PATH | 3 | Search path for commands. |
PS1 | 3 | Primary command prompt string. |
PS2 | 3 | Prompt string for line continuations. |
PS3 | 5 | Prompt string for select command. |
PS4 | 9 | Prompt string for xtrace option. |
PPID | 8 | Process ID of parent process. |
PWD | 3 | Current working directory. |
RANDOM | 9 | Random number between 0 and 32767 (2215-1). |
REPLY | 5,7 | User's response to select command; result of read command if no variable names given. |
SECONDS | 3 | Number of seconds since shell was invoked. |
SHELL | 3 | Full pathname of shell. |
TMOUT | 10 | If set to a positive integer, number of seconds between commands after which shell automatically terminates. |
VISUAL | 2 | Used to set editing mode. |
These are the operators that are used with the [[...]] construct. They can be logically combined with &&("and") and || ("or") and grouped with parenthesis.
Operator | True If... |
---|---|
-a file | file exists. |
-b file | file is a block device file. |
-c file | file is a character device file. |
-d file | file is a directory. |
-f file | file is a regular file. |
-g file | file has its setgid bit set. |
-k file | file has its sticky bit set. |
-n string | string is non-null. |
-o option | option is set. |
-p file | file is a pipe or named pipe (FIFO file). |
-r file | file is readable. |
-s file | file is not empty. |
-t N | File descriptor N points to a terminal. |
-u file | file has its setuid bit set. |
-w file | file is writeable. |
-x file | file is executable, or file is a directory that can be searched. |
-z string | string is null. |
-G file | file's group ID is the same as that of the shell. |
-L file | file is a symbolic link. |
-O file | file is owned by the shell's user ID. |
-S file | file is a socket. |
fileA -nt fileB | fileA is newer than fileB. |
fileA -ot fileB | fileA is older than fileB. |
fileA -ef fileB | fileA and fileB point to the same file. |
string = pattern | string matches pattern (which can contain wildcards). |
string != pattern | string does not match pattern. |
stringA < stringB | stringA comes before stringB in dictionary order. |
stringA > stringB | stringA comes after stringB in dictionary order. |
exprA -eq exprB | Arithmetic expressions exprA and exprB are equal. |
exprA -ne exprB | Arithmetic expressions exprA and exprB are not equal. |
exprA -lt exprB | exprA is less than exprB. |
exprA -gt exprB | exprA is greater than exprB. |
exprA -le exprB | exprA is less than or equal to exprB. |
exprA -ge exprB | exprA is greater than or equal to exprB. |
These are arguments to the typeset command.
Option | Meaning |
---|---|
With no option, create local variable within function. | |
-L | Left justify and remove leading blanks. |
-R | Right justify and remove trailing blanks. |
-f | With no arguments, prints all function definitions. |
-f fname | Prints the definition of function fname. |
+f | Prints all function names. |
-ft | Turns on trace mode for named function(s). |
+ft | Turns off trace mode for named function(s). |
-fu | Defines given name(s) as autoloaded function(s). |
-i | Declare variable as an integer. |
-l | Convert all letters to lowercase. |
-r | Make variable read-only. |
-u | Convert all letters to uppercase. |
-x | Export variable, i.e., put in environment so that it is passed to subshells |
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: | $ 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.[7] |
Purpose: | Setting a variable to a default value if it is undefined. |
Example: | |
${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. Omittingmessage produces the default message parameter null or not set. |
Purpose: | Catching errors that result from variables being undefined. |
Example: | {count |
${varname:+ word} | If varname exists and isn't null, return word; otherwise return null. |
Purpose: | Testing for the existence of a variable. |
Example: | $ returns 1 (which could mean "true") if count is defined. |
--------------------------------
处 理和(或)扩展变量
-
${parameter}
-
与$parameter相同, 也就是变量parameter的值. 在某些上下文中, ${parameter}很少会产生混淆.
可 以把变量和字符串组合起来使用.
${parameter-default}, ${parameter:-default}
-
${parameter-default} -- 如果变量parameter没被声明, 那么就使用默认值.
${parameter:-default} -- 如果变量parameter没被设置, 那么就使用默认值.
-
${parameter=default}, ${parameter:=default}
-
${parameter=default} -- 如果变量parameter没声明, 那么就把它的值设为default.
${parameter:=default} -- 如果变量parameter没设置, 那么就把它的值设为default.
这两种形式基本上是一样的. 只有在变量$parameter被声明并且被设置为 null值的时候, :才会引起这两种形式的不同. [1] 如上边所示.
${parameter+alt_value}, ${parameter:+alt_value}
-
${parameter+alt_value} -- 如果变量parameter被声明了, 那么就使用alt_value, 否则就使用null字符串.
${parameter:+alt_value} -- 如果变量parameter被设置了, 那么就使用alt_value, 否则就使用null字符串.
这两种 形式绝大多数情况下都一样. 只有在parameter被声明并且设置为null值的时候, 多出来的这个:才会引起这两种形式的不同, 具体请看下边的例子.
${parameter?err_msg}, ${parameter:?err_msg}
-
${parameter?err_msg} -- 如果parameter已经被声明, 那么就使用设置的值, 否则打印err_msg错误消息.
${parameter:?err_msg} -- 如果parameter已经被设置, 那么就使用设置的值, 否则打印err_msg错误消息.
这两种形式绝大多数情况都是一样 的. 和上边所讲的情况一样, 只有在parameter被声明并设置为null值的时候, 多出来的:才会引起这两种形式的不同.