shell 脚本学习之 字符串比较

来源:互联网 发布:mac上ps破解文件 编辑:程序博客网 时间:2024/05/16 07:53

本片主要说明一些字符串比较中的注意事项

主要包括了字符串 相等、不等、长度、空字符串 以及逻辑与、逻辑或的内容,具体内容见下面的脚本:

#!/bin/bash# test string ordera="ss"b="abc"c="ss"echo "----------------------------------------------------------------------------"echo " test for string compare with \"!=\",\"=\",\"-z\",\"-n\",is a null str ;test string is \"$a\"  and \"$b\""echo "----------------------------------------------------------------------------"echo "*************----------*********************"echo "-----------"echo "test \"=\"  等号运算,比较两个字符串相等"echo "-----------"echo "if [ \$a = \$b ]; then  用=来比较两个字符串是否相等, 注意不是==符号 ,注意语句中的空格符号一定要预留好,下面的一些语句中的空格格式和本句类似"if [ $a = $b ]; then    echo "$a == $b : a = b"else    echo "-----------"    echo "test \"!=\",不等号运算,比较两个字符串不相等"    echo "-----------"    if [ $a != $c ]; then        echo "$a == $c :a !=c "    else        echo "$a == $c : a ==c "    fifiecho "-----------"echo "test \"-z\",字符串长度为0运算,为0返回真"echo "-----------"if [ -z $a ]then    echo "-z $a : 字符串长度为 0"else    echo "-z $a : 字符串长度不为 0"fiecho "-----------"echo "test \"-n\",字符串长度不为0运算,不为0返回真"echo "-----------"if [ -n $a ]then    echo "-n $a : 字符串长度不为 0"else    echo "-n $a : 字符串长度为 0"fiecho "-----------"echo "test is a null str"echo "-----------"if [ $a ]thenecho "$a : 字符串不为空"elseecho "$a : 字符串为空"fia="aaa"b="bbb"echo "----------------------------------------------------------------------------"echo " test string  with \"&&\",\"||\";test string is \"$a\"  and \"$b\""echo "----------------------------------------------------------------------------"echo "-----------"echo "test \"&&\",逻辑与运算"echo "-----------"if [[ $a = $a && $b = $b ]]thenecho "[[ \$a = \$a && \$b = \$b ]]返回 true"elseecho "[[ \$a = \$a && \$b = \$b ]]返回 false"fiecho "-----------"echo "test \"||\",逻辑或运算"echo "-----------"if [[ $a = $b || $b = $b ]]thenecho "[[ \$a = \$b || \$b = \$b ]]返回 true"elseecho "[[ \$a = \$b || \$b = \$b ]]返回 false"fiecho "*************----------*********************"