shell的数学运算
1 branches@ubuntu:~$ var1=$[2 * 5] 2 branches@ubuntu:~$ echo $var1 3 10 4 branches@ubuntu:~$ var2=$[$var1 + 8] 5 branches@ubuntu:~$ echo $var2 6 18 7 branches@ubuntu:~$ var2=$[$var1+8.6] <==Bash Shell只能处理整数运算 8 -bash: 10+8.6: 语法错误: 无效的算术运算符 (错误符号是 ".6")
shell的浮点数运算
1 branches@ubuntu:~$ bc 2 bc 1.06.95 3 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. 4 This is free software with ABSOLUTELY NO WARRANTY. 5 For details type `warranty'. 6 23.4+7.035 7 30.435 8 3.14*(3+4) 9 21.98 10 quit 11 branches@ubuntu:~$
字符串大小比较
1 branches@ubuntu:~/Scripts$ cat badtest.sh 2 #!/bin/bash 3 #mis-using string comparsions 4 # 5 val1=baseball 6 val2=hockey 7 # 8 #if [ $val1 > $val2 ] <== 正确写法 9 if[$val1 > $val2] 10 #会报错'badtest.sh: 7: [: missing ]' <== if和[之间一定要有' '空格 11 #会出现文件 hockey],因为'>'被当做重定向符 <== '>'前夹转义字符成'>' & '$val2'和']'之间加' '空格 12 then 13 echo "$val1 is greater than $val2" 14 else 15 echo "$val1 is less than $val2" 16 fi
在比较测试中,大写字母被认为是小于小写字母的。与sort命令恰好相反
注意,test命令和测试表达式使用标准的数学表比较符号来表示字符串比较,而用文本代码来表示数值比较。这个细微的特性被很多程序猿理解反了
文件测试
-d file 检查file是否存在并是一个目录 -e file 检查file是否存在 -f file 检查file是否存在并是一个文件 -r file 检查file是否存在并可读 -s file 检查file是否存在并非空 -w file 检查file是否存在并可写 -x file 检查file是否存在并可执行 -O file 检查file是否存在并属当前用户所有 -G file 检查file是否存在并默认组与当前用户相同 file1 -nt file2 检查file1是否存比file2新 file1 -ot file2 检查file1是否存比file2旧