- 单括号的使用
- 双括号
#【前言】
shell中的中括号在条件测试中是使用最频繁的,无论是中括号还是双中括号:
- 算数比较: 比如一个变量是否大于1 ,[ $free -gt 1 ]
- 文件测试: 比如一个文件是否存在,[ -e /opt/kiro ]
- 字符串比较: 比如字符串是否相同,[[ $home = $user ]]
- 文件测试:
[root@Kiro shell]# [ -d /etc/passwd ] && echo 存在 || echo 不存在 不存在
- 整数值比较:
[root@Kiro shell]# ls |wc -l 9 [root@Kiro shell]# num=`ls |wc -l` [root@Kiro shell]# echo $num 9 [root@Kiro shell]# [ $num -gt 5 ] && echo 当前目录文件大于5 当前目录文件大于5 [root@Kiro shell]#双括号
- 字符串比较
[root@Kiro shell]# vim test.sh !/bin/bash read -p "请输入你的文件名: " file if [[ $file == *.sh ]]; then echo "这是一个shell脚本" fi [root@Kiro shell]# bash test.sh 请输入你的文件名: star.sh 这是一个shell脚本
==代表比较,=代表赋值
#【总结】
其实test 命令是可以代替[]中括号的,还可以省不少事!例如:
if [ $free -gt 0 ]; then echo "非0";fi
等价于
if test $free -gt 0; then echo "非0";fi
注:这里的$free是我提前定义好的


![Shell中[中括号]的用法详解——条件测试必会 Shell中[中括号]的用法详解——条件测试必会](http://www.mshxw.com/aiimages/31/841922.png)
