shell 变量和参数

来源:互联网 发布:淘宝发布虚拟宝贝教程 编辑:程序博客网 时间:2024/05/01 00:07
 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)

WildcardMatches?Any single character*Any string of characters[set]Any character in set[!set]Any character not in set2)ExpressionMatches[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 dash3)UtilityPurposecatCopy input to outputgrepSearch for strings in the inputsortSort lines in the inputcutExtract columns from inputsedPerform editing operations on inputtrTranslate characters in the input to other characters4)
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.

CommandChapterSummary:7Do nothing (just do expansions of arguments)..4Read file and execute its contents in current shell.alias3Set up shorthand for command or command line.bg8Put job in background.break5

Exit from surrounding for, select, while, oruntil loop.

case5Multi-way conditional construct.cd1Change working directory.continue 

Skip to next iteration of for, select, while, or until loop.

echo4Expand and print arguments (obsolete).exec9Replace shell with given program.exit5Exit from shell.export3Create environment variables.eval7Process arguments as a command line.fc2Fix command (edit history file).fg8Put background job in foreground.for5Looping construct.function4Define function.getopts6Process command-line options.if5Conditional construct.jobs1List background jobs.kill8Send signal to process.let6Arithmetic variable assignment.newgrp Start new shell with new group ID.print1Expand and print arguments on standard output.pwd1Print working directory.read7Read a line from standard input.readonly6Make variables read-only (unassignable).return5Return from surrounding function or script.select5Menu generation construct.set3Set options.shift6Shift command-line arguments.time Run command and print execution times.trap8Set up signal-catching routine.typeset6Set special characteristics of variables.ulimit10Set/show process resource limits.umask10Set/show file permission mask.unalias3Remove alias definitions.unset3Remove definitions of variables or functions.until5Looping construct.wait8Wait for background job(s) to finish.whence3Identify source of command.while5Looping construct.7)
Built-in Shell Variables

VariableChapterMeaning#4Number of arguments given to current process.- Options given to shell on invocation.?5Exit status of previous command.$8Process ID of shell process._ Last argument to previous command.!8Process ID of last background command.CDPATH3List of directories for cd command to search.COLUMNS3

Width of display in columns (for editing modes and select).

EDITOR2

Used to set editing mode; also used by mail and other programs.

ERRNOAError number of last system call that failed.ENV3

Name of file to run as environment file when shell is invoked.

FCEDIT2Default editor for fc command.FPATH4Search path for autoloaded functions.IFS7

Internal field separator: list of characters that act as word separators. Normally set to SPACE, TAB, and NEWLINE.

HISTFILE2Name of command history file.HISTSIZE2Number of lines kept in history file.HOME3Home (login) directory.LINENO9Number of line in script or function that just ran.LINES3Height of display in lines (for select command).MAIL3Name of file to check for new mail.MAILCHECK3How often (in seconds) to check for new mail.MAILPATH3

List of file names to check for new mail, if MAIL is not set.

OLDPWD3Previous working directory.OPTARG6Argument to option being processed by getopts.OPTIND6Number of first argument after options.PATH3Search path for commands.PS13Primary command prompt string.PS23Prompt string for line continuations.PS35Prompt string for select command.PS49Prompt string for xtrace option.PPID8Process ID of parent process.PWD3Current working directory.RANDOM9

Random number between 0 and 32767 (2215-1).

REPLY5,7

User's response to select command; result of read command if no variable names given.

SECONDS3Number of seconds since shell was invoked.SHELL3Full pathname of shell.TMOUT10

If set to a positive integer, number of seconds between commands after which shell automatically terminates.

VISUAL2Used 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.

OperatorTrue If...-a filefile exists.-b filefile is a block device file.-c filefile is a character device file.-d filefile is a directory.-f filefile is a regular file.-g filefile has its setgid bit set.-k filefile has its sticky bit set.-n stringstring is non-null.-o optionoption is set.-p filefile is a pipe or named pipe (FIFO file).-r filefile is readable.-s filefile is not empty.-t NFile descriptor N points to a terminal.-u filefile has its setuid bit set.-w filefile is writeable.-x file

file is executable, or file is a directory that can be searched.

-z stringstring is null.-G filefile's group ID is the same as that of the shell.-L filefile is a symbolic link.-O filefile is owned by the shell's user ID.-S filefile is a socket.fileA -nt fileBfileA is newer than fileB.fileA -ot fileBfileA 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 != patternstring 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 exprBexprA is less than exprB.exprA -gt exprBexprA is greater than exprB.exprA -le exprBexprA is less than or equal to exprB.exprA -ge exprBexprA is greater than or equal to exprB.

9)Typeset Options

These are arguments to the typeset command.

OptionMeaning With no option, create local variable within function.-LLeft justify and remove leading blanks.-RRight justify and remove trailing blanks.-fWith no arguments, prints all function definitions.-f fnamePrints the definition of function fname.+fPrints all function names.-ftTurns on trace mode for named function(s).+ftTurns off trace mode for named function(s).-fuDefines given name(s) as autoloaded function(s).-iDeclare variable as an integer.-lConvert all letters to lowercase.-rMake variable read-only.-uConvert all letters to uppercase.-x

Export variable, i.e., put in environment so that it is passed to subshells

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

原创粉丝点击