How to compare strings under Linux

Source: Internet
Author: User

A="$1"B="$2" #判断字符串是否相等 if [ "$A" = "$B" ];thenecho "[ = ]"fi #判断字符串是否相等,与上面的=等价 if [ "$A" == "$B" ];thenecho "[ == ]"fi #注意:==的功能在[[]]和[]中的行为是不同的,如下  #如果$a以”a”开头(模式匹配)那么将为true  if [[ "$A" == a* ]];thenecho "[[ ==a* ]]"fi #如果$a等于a*(字符匹配),那么结果为true if [[ "$A" == "a*" ]];thenecho "==/"a*/""fi  #File globbing(通配) 和word splitting将会发生, 此时的a*会自动匹配到对应的当前以a开头的文件 #如在当前的目录中有个文件:add_crontab.sh,则下面会输出ok #if [ "add_crontab.sh" == a* ];then  #echo "ok" #fi if [ "$A" == a* ];thenecho "[ ==a* ]"fi #如果$a等于a*(字符匹配),那么结果为true if [ "$A" == "a*" ];thenecho "==/"a*/""fi  #字符串不相等 if [ "$A" != "$B" ];thenecho "[ != ]"fi #字符串不相等 if [[ "$A" != "$B" ]];thenecho "[[ != ]]"fi #字符串不为空,长度不为0 if [ -n "$A" ];thenecho "[ -n ]"fi #字符串为空.就是长度为0. if [ -z "$A" ];thenecho "[ -z ]"fi #需要转义<,否则认为是一个重定向符号 if [ $A /< $B ];thenecho "[ < ]"fi if [[ $A < $B ]];thenecho "[[ < ]]"fi #需要转义>,否则认为是一个重定向符号 if [ $A /> $B ];thenecho "[ > ]"fi if [[ $A > $B ]];thenecho "[[ > ]]"fi

How to compare strings under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.