加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 条件表达式如何比较字符串?

发布时间:2020-12-16 01:19:52 所属栏目:安全 来源:网络整理
导读:#!/usr/bin/env bashecho 'Using conditional expression:'[[ ' ' '0' ]] echo ok || echo not ok[[ ' a' '0a' ]] echo ok || echo not okecho 'Using test:'[ ' ' '0' ] echo ok || echo not ok[ ' a' '0a' ] echo ok || echo not ok 输出是: Using co
#!/usr/bin/env bash
echo 'Using conditional expression:'
[[ ' ' < '0' ]] && echo ok || echo not ok
[[ ' a' < '0a' ]] && echo ok || echo not ok
echo 'Using test:'
[ ' ' &; '0' ] && echo ok || echo not ok
[ ' a' &; '0a' ] && echo ok || echo not ok

输出是:

Using conditional expression:
ok
not ok
Using test:
ok
ok

bash –version:GNU bash,版本4.2.45(1)-release(x86_64-pc-linux-gnu)

uname -a:Linux linuxmint 3.8.0-19-generic

Bash手册说:

When used with [[,the < and > operators sort lexicographically using the current locale. The test command sorts using ASCII ordering.

这归结为分别使用strcoll(3)或strcmp(3).

使用以下程序(strcoll_strcmp.c)来测试:

#include <stdio.h>
#include <string.h>
#include <locale.h>

int main(int argc,char **argv)
{
    setlocale(LC_ALL,"");

    if (argc != 3) {
        fprintf(stderr,"Usage: %s str1 str2n",argv[0]);
        return 1;
    }

    printf("strcoll('%s','%s'): %dn",argv[1],argv[2],strcoll(argv[1],argv[2]));
    printf("strcmp('%s',strcmp(argv[1],argv[2]));

    return 0;
}

注意区别:

$LC_ALL=C ./strcoll_strcmp ' a' '0a'
strcoll(' a','0a'): -16
strcmp(' a','0a'): -16

$LC_ALL=en_US.UTF-8 ./strcoll_strcmp ' a' '0a'
strcoll(' a','0a'): 10
strcmp(' a','0a'): -16

究竟为什么这些比较,我不确定.这必须归功于一些英语词典排序规则.我认为确切的规则在ISO 14651 Method for comparing character strings and description of the common template tailorable ordering和附带的模板表中描述. Glibc在libc / localedata / locales下的源代码树中包含此数据.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读