if的[]和[[]]

来源:互联网 发布:python thinter视频 编辑:程序博客网 时间:2024/06/05 06:11

[]是bash里test的同义词,比如[ -d filename ]和test -d filename的结果是一样的,逻辑测试使用-a、-o
[[]]比[]通用,逻辑测试使用&&、||

#!/bin/bashx=$1if [ -d $x ];then        echo okelse        echo "not equel"fi----------------------------[root@localhost shelltest]# test -d /root && echo llll

在[]里面,使用-eq的时候,需要用整数来做参数,如果是非整数就会提示报错,而[[]]则直接把非整数的字符串转成了0(),而不会去检查并显示报错内容。

if [ $x -eq $y ]时[root@localhost shelltest]# ./teststring.sh 1 ad./teststring.sh: line 4: [: ad: integer expression expected当if [[ $x -eq $y ]]时[root@localhost shelltest]# ./teststring.sh ad adok[root@localhost shelltest]# ./teststring.sh 1 anot equel[root@localhost shelltest]# ./teststring.sh aa 0ok[root@localhost shelltest]# ./teststring.sh 0 aaok

[]和[[]]都不支持+-*/数学运算符

整数的比较
注意前面都是有个符号-

eq等于ne不等于gt大于ge大于等于lt小于le小于等于例if [ $x -eq $y ]if [[ $x -gt $y ]]if [ "$x" -eq "$y" ]if [[ "$x" -eq "$y" ]]
>大于>=大于等于<小于<=小于等于例if [[ $x > $y ]]if (( $x > $y ))
注:if [ $x > $y ]会一直为true,可以改成if [ $x \> $y ],也就是把符号>转义(包括字符串(**ASCII中对应的顺序大小**)和整数)。(if [ "$x" \> "$y" ])

字符串的比较
=等于,效果和==是一样的

if [ $x = $y ]if [[ $x = $y ]]if [ $x == $y ]if [[ $x == $y ]]if [[ $x = "abc" ]]

-z测试是否为空,为空则为true

if [ -z "$x" ]if [ -z $x ]

-n测试是否不为空,不为空则为true

if [ -n "$x" ]

注:需要有双引号,负责一直为true

原创粉丝点击