- 字符串比较
-
字符串相等比较
相等:在[]中使用==或=
[root@master Workspace]# ./test.sh true [root@master Workspace]# cat test.sh #! /bin/sh a="test" if [ "$a" = "test" ];then echo "true" fi # or [root@master Workspace]# ./test.sh true [root@master Workspace]# cat test.sh #! /bin/sh a="test" if [ "$a" == "test" ];then echo "true" fi
不等:在[]中使用!=
[root@master Workspace]# cat test.sh #! /bin/sh a="test" if [ "$a" != "test" ];then echo "true" fi [root@master Workspace]# ./test.sh
-
字符串包含
在[[ ]]中使用=~
[root@master Workspace]# ./test.sh true [root@master Workspace]# cat test.sh #! /bin/sh a="test" if [[ "$a" =~ "es" ]];then echo "true" fi
不包含
[root@master Workspace]# cat test.sh #! /bin/sh a="test" if [[ ! "$a" =~ "es" ]];then echo "true" fi
-
模式匹配
[root@master Workspace]# cat test.sh #! /bin/sh a="test" # 以t开头 if [[ "$a" == t* ]];then echo "true" fi [root@master Workspace]# ./test.sh true
shell脚本#为注释符号,那么如何判断以#开头呢?
[root@master Workspace]# ./test.sh true [root@master Workspace]# cat test.sh #! /bin/sh a="#test" if [[ "$a" == ''#*'' ]];then echo "true" fi # or [root@master Workspace]# ./test.sh true [root@master Workspace]# cat test.sh #! /bin/sh a="#test" if [[ "$a" == \#* ]];then echo "true" fi