Shell中的[]

Shell中的[],没太搞明白,请高手指点。

 
ricky@ricky-desktop:~$ a=0
ricky@ricky-desktop:~$ if [ $a ]; then
> echo "Gooooood"
> else
> echo "Baaaaaaad"
> fi
Gooooood
ricky@ricky-desktop:~$ a=1
ricky@ricky-desktop:~$ if [ $a ]; then echo "Gooooood"; else echo "Baaaaaaad"; fi
Gooooood
ricky@ricky-desktop:~$ a="string"
ricky@ricky-desktop:~$ if [ $a ]; then echo "Gooooood"; else echo "Baaaaaaad"; fi
Gooooood
ricky@ricky-desktop:~$ a=
ricky@ricky-desktop:~$ if [ $a ]; then echo "Gooooood"; else echo "Baaaaaaad"; fi
Baaaaaaad
ricky@ricky-desktop:~$ a=100
ricky@ricky-desktop:~$ if [ $a ]; then echo "Gooooood"; else echo "Baaaaaaad"; fi
Gooooood
ricky@ricky-desktop:~$ unset a
ricky@ricky-desktop:~$ if [ $a ]; then echo "Gooooood"; else echo "Baaaaaaad"; fi
Baaaaaaad
ricky@ricky-desktop:~$


多些几位大虾的指点,上面如果用string存在不存在来解释,那么下面怎么解释:

ricky@ricky-desktop:~$ a=1
ricky@ricky-desktop:~$ if [ ! $a ] ; then echo "Goooooood"; else echo "Baaaaaad"; fi
Baaaaaad
ricky@ricky-desktop:~$ a=0
ricky@ricky-desktop:~$ if [ ! $a ] ; then echo "Goooooood"; else echo "Baaaaaad"; fi
Baaaaaad
ricky@ricky-desktop:~$ a=true
ricky@ricky-desktop:~$ if [ ! $a ] ; then echo "Goooooood"; else echo "Baaaaaad"; fi
Baaaaaad
ricky@ricky-desktop:~$ a=false
ricky@ricky-desktop:~$ if [ ! $a ] ; then echo "Goooooood"; else echo "Baaaaaad"; fi
Baaaaaad
ricky@ricky-desktop:~$ 

This entry was posted in 脚本语言 and tagged . Bookmark the permalink.

10 Responses to Shell中的[]

  1. mjxian says:

    可以看 man 的吧?就是 test 的另一种表达方式。

    TEST(1) User Commands TEST(1)

    NAME
    test – check file types and compare values

    SYNOPSIS
    test EXPRESSION
    test

    [ EXPRESSION ]
    [ ]
    [ OPTION

    DESCRIPTION
    Exit with the status determined by EXPRESSION.

  2. gengmao says:

    http://en.wikipedia.org/wiki/Test_(Unix)

    also in the man page of test:
    string True if string is not the null string.

  3. Tonyliao says:

    在shell中,变量用不定义类型,没有布尔类型
    if的判断,如果是数字,只有1,0,非0即1。如果是字符串,有非空,空。
    看一下perl语言入门第四版,跟里面讲的一样

  4. Tonyliao says:

    顺便问一句,rickyzhu在深圳?

  5. ricky says:

    对的,深圳大冲

  6. ricky says:

    那后面的怎么解释,string的解释可以理解, !0或者!1 为什么都返回false呢?

  7. tonyliao says:

    你要注意,a=0; !$a 不代表非0,而是变成一个字符串了,是!0的组合
    举个例子
    localdomain ~]# cat test.sh
    #!/bin/bash
    a=0
    b=!$a
    echo “$b”
    得出来的结果是!0

  8. tonyliao says:

    加我gmail吧,明天有个广州技术沙龙在深圳举行,有兴趣一起去不?
    ps,你们公司需要招聘linux 系统管理员或DBA吗?我在求职中

  9. Ricky says:

    需要在实验一下, !$a 跟 ! $a 还是略有不同的

Leave a Reply

Your email address will not be published. Required fields are marked *