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

前端之家收集整理的这篇文章主要介绍了bash – 条件表达式如何比较字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. #!/usr/bin/env bash
  2. echo 'Using conditional expression:'
  3. [[ ' ' < '0' ]] && echo ok || echo not ok
  4. [[ ' a' < '0a' ]] && echo ok || echo not ok
  5. echo 'Using test:'
  6. [ ' ' \< '0' ] && echo ok || echo not ok
  7. [ ' a' \< '0a' ] && echo ok || echo not ok

输出是:

  1. Using conditional expression:
  2. ok
  3. not ok
  4. Using test:
  5. ok
  6. 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)来测试:

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <locale.h>
  4.  
  5. int main(int argc,char **argv)
  6. {
  7. setlocale(LC_ALL,"");
  8.  
  9. if (argc != 3) {
  10. fprintf(stderr,"Usage: %s str1 str2\n",argv[0]);
  11. return 1;
  12. }
  13.  
  14. printf("strcoll('%s','%s'): %d\n",argv[1],argv[2],strcoll(argv[1],argv[2]));
  15. printf("strcmp('%s',strcmp(argv[1],argv[2]));
  16.  
  17. return 0;
  18. }

注意区别:

  1. $LC_ALL=C ./strcoll_strcmp ' a' '0a'
  2. strcoll(' a','0a'): -16
  3. strcmp(' a','0a'): -16
  4.  
  5. $LC_ALL=en_US.UTF-8 ./strcoll_strcmp ' a' '0a'
  6. strcoll(' a','0a'): 10
  7. strcmp(' a','0a'): -16

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

猜你在找的Bash相关文章