shell 变量和参数
来源:互联网 发布:淘宝发布虚拟宝贝教程 编辑:程序博客网 时间:2024/05/01 00:07
$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)
?
Any single character*
Any string of characters[set]Any character in set[!set]Any character not in set2)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.
Exit from surrounding for, select, while, oruntil loop.
case5Multi-way conditional construct.cd1Change working directory.continueSkip 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
Width of display in columns (for editing modes and select).
EDITOR2Used to set editing mode; also used by mail and other programs.
ERRNOAError number of last system call that failed.ENV3Name of file to run as environment file when shell is invoked.
FCEDIT2Default editor for fc command.FPATH4Search path for autoloaded functions.IFS7Internal 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.MAILPATH3List 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.RANDOM9Random number between 0 and 32767 (2215-1).
REPLY5,7User'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.TMOUT10If set to a positive integer, number of seconds between commands after which shell automatically terminates.
VISUAL2Used to set editing mode.8)Test OperatorsThese are the operators that are used with the [[...]] construct. They can be logically combined with&& ("and") and || ("or") and grouped with parenthesis.
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 fileBfileA and fileB point to the same file.
string = patternstring matches pattern (which can contain wildcards).
string != patternstring does not match pattern.stringA < stringBstringA comes before stringB in dictionary order.
stringA > stringBstringA comes after stringB in dictionary order.
exprA -eq exprBArithmetic expressions exprA and exprB are equal.
exprA -ne exprBArithmetic 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 OptionsThese are arguments to the typeset command.
Export variable, i.e., put in environment so that it is passed to subshells
10)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.
:?
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.
:+
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值的时候, 多出来的:才会引起这两种形式的不同.
- shell 变量和参数
- shell 变量和参数
- shell 位置变量和特殊变量参数
- [shell]Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- Shell变量和参数的介绍
- shell里面内部变量和参数标识
- shell入门教程(2)-变量和参数
- shell和命令行参数有关的变量
- shell特殊变量$0,$#,$@,$*,$?,$$和命令行参数
- Shell怪异参数和变量--待整理
- [Shell]特殊变量$0$#$*$@$?和命令行参数
- shell位置参数和特殊变量
- Shell特殊变量:$0, $#, $*, $@, $?, $$和命令行参数
- Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- 六、Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
- ipa图片资源
- JAVA抓取网站网页内容
- SpringMVC 实现根据不同的请求类型(请求方法method=GetOrPost)分别响应
- ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
- dma_alloc_writecombine
- shell 变量和参数
- Facebook手机面市已晚?
- IBATIS 查询操作 查询条件包含多个元素
- ComInterfaceType Enumeration
- JSOUP初探
- UV Atlas Command-Line Tool (uvatlas.exe)
- android:windowSoftInputMode
- VC 下Microsoft Speech SDK5.1开发小结
- Windows 7桌面显示图标窗口类名称