一、特殊变量
$0:当前脚本的文件名
$n:传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2
$#:传递给脚本或函数的参数个数
$*:传递给脚本或函数的所有参数
$@:传递给脚本或函数的所有参数。被双引号(" ")包含时,与 $* 稍有不同,下面将会讲到
$?:上个命令的退出状态,或函数的返回值
$$:当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID
二、判断条件test
条件表达式 | 意义 |
1.文件类检测,例如[ -e /tmp/a.log ]。如非特别说明,则所有文件类操作都会追踪到软链接的源文件。 | |
-e file | 文件是否存在(exist) |
-f file | 文件是否存在且为普通文件(file) |
-d file | 文件是否存在且为目录(directory) |
-b file | 文件是否存在且为块设备block device |
-c file | 文件是否存在且为字符设备character device |
-S file | 文件是否存在且为套接字文件Socket |
-p file | 文件是否存在且为命名管道文件FIFO(pipe) |
-L file | 文件是否存在且是一个链接文件(Link) |
2. 文件属性检测,如test -r /tmp/a.log。如非特别说明,则所有文件类操作都会追踪到软链接的源文件。 | |
-r file | 文件是否存在且当前用户可读 |
-w file | 文件是否存在且当前用户可写 |
-x file | 文件是否存在且当前用户可执行 |
-u file | 文件是否存在且设置了SUID |
-g file | 文件是否存在且设置了SGID |
-k file | 文件是否存在且设置了sbit(sticky bit) |
-s file | 文件是否存在且大小大于0字节,即用于检测文件是否为非空白文件 |
-N file | 文件是否存在,且自上次read后是否被modify |
3. 两个文件之间的比较,如:test file1 -nt file2 | |
file1 -nt file2 | (newer than)判断file1是否比file2新 |
file1 -ot file2 | (older than)判断file1是否比file2旧 |
file1 -ef file2 | (equal file)判断file2与file2是否为同一文件,可用在判断hard link的判定上。主要意义在判定,两个文件是否均指向同一个分区上的同一个inode |
4. 两个整数之间的判定,支持正负数,但不支持小数。例如test n1 -eq n2 | |
int1 -eq int2 | 两数值相等(equal) |
int1 -ne int2 | 两数值不等(not equal) |
int1 -gt int2 | n1大于n2(greater than) |
int1 -lt int2 | n1小于n2(less than) |
int1 -ge int2 | n1大于等于n2(greater than or equal) |
int1 -le int2 | n1小于等于n2(less than or equal) |
5. 判定字符串 | |
-z string | (zero)判定字符串是否为空?若string为空字符串,则为true |
string -n string | 判定字符串是否非空?若string为空字符串,则false。注:-n可省略 |
string1 = string2 string1 == string2 | string1和string2是否相同。相同则返回true。"=="和"="等价,但"="可移植性更好 |
str1 != str2 | str1是否不等于str2,若不等,则返回true |
str1 > str2 | str1字母顺序是否大于str2,若大于,则返回true |
str1 < str2 | str1字母顺序是否小于str2,若小于,则返回true |
6.逻辑运算符,例如:test -r filename -a -x filename | |
-a或&& | (and)两表达式同时为true时才为true。"-a"只能在test或[]中使用,&&只能在[[]]中使用 |
-o或|| | (or)两表达式任何一个true则为true。"-o"只能在test或[]中使用,||只能在[[]]中使用 |
! | 对表达式取反 |
( ) | 用于改变表达式的优先级 |
三、循环体语句
1、if语句
if [ -d $1 ] then echo "this is a directory!" else echo "this is not a directory!" fi |
2、elif语句
if [ $1 -eq $2 -a $1 = 1 ] then echo "param1 == param2 and param1 = 1" elif [ $1 -ne $2 -o $1 = 2 ] then echo "param1 != param2 or param1 = 2" else echo "others" fi |
3、for语句
for var in 1 2 3 4 5 6 7 8 9 10 do echo "number is $var" done |
4、select语句
select var in "java" "c++" "php" "linux" "python" "ruby" "c#" do break done echo "you selected $var" |
5、case语句
case $op in a) echo "you selected a";; b) echo "you selected b";; c) echo "you selected c";; *) echo "error" esac |
6、while语句
num=1 sum=0 while [ $num -le 100 ] do sum=`expr $sum + $num` num=`expr $num + 1` done #sleep 5 echo $sum |
7、continue与break
i=0 while [ $i -le 100 ] do i=`expr $i + 1` if [ $i -eq 5 -o $i -eq 10 ] then continue; else echo "this number is $i" fi if [ $i -eq 15 ] then break; fi done |