Chinaunix首页 | 论坛 | 博客
  • 博客访问: 844335
  • 博文数量: 133
  • 博客积分: 7117
  • 博客等级: 少将
  • 技术积分: 1846
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-16 21:30
文章分类

全部博文(133)

文章存档

2012年(1)

2011年(4)

2010年(2)

2009年(57)

2008年(69)

分类:

2009-01-16 16:47:12

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 )中执行的命令组
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结构如果用在有意义的场合中, 往往都很难理解, 并且技巧性很高. 所以最好的方法就是尽量避免使用它.《摘自: 3.9.1_cn/html/loopcontrol.html》

{if ($1 == "'"$module"'") n = "yes";}
"'"表示输入一个'单引号
所以分解为
"'"
$module
"'"


exec 9<&0
while read line; do echo 'luther.gliethttp '$line; done --------------------------------
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
$ 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 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
        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个字符,?表示一个字符
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
摘自:
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
2)
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
3)
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
4)
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.
print 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.
7)
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).
MAIL 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.

8)Test Operators

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.

9)Typeset Options

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

10)
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:

$ 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. 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:

$ 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值的时候, :才会引起这两种形式的不同. 如上边所示.

${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值的时候, 多出来的:才会引起这两种形式的不同.

阅读(5010) | 评论(0) | 转发(1) |
0

上一篇:debian package

下一篇:arm EABI and the related

给主人留下些什么吧!~~