2012-08-16 49 views
17

在bash我可以寫出如下測試Bash - 測試一個字符串是否比另一個'更大' - 它在內部是如何工作的?

[[ "f" > "a" ]] 

這導致返回0,即如此。 bash如何實際執行此字符串比較?從我的理解>做一個整數比較。它是否嘗試比較操作數的ASCII值?

+1

是的我懷疑它有一個多態的交易進行在哪裏>意味着兩個字符串和另一個兩個數字的一​​件事。不過,我不是一個有經驗的bash編碼器。 – VoronoiPotato 2012-08-16 14:31:44

回答

8

help test

STRING1 > STRING2 
       True if STRING1 sorts after STRING2 lexicographically. 

在內部,bash的任一使用該strcoll()strcmp()

else if ((op[0] == '>' || op[0] == '<') && op[1] == '\0') 
    { 
    if (shell_compatibility_level > 40 && flags & TEST_LOCALE) 
     return ((op[0] == '>') ? (strcoll (arg1, arg2) > 0) : (strcoll (arg1, arg2) < 0)); 
    else 
     return ((op[0] == '>') ? (strcmp (arg1, arg2) > 0) : (strcmp (arg1, arg2) < 0)); 
    } 

後者實際上比較ASCII碼,前(當區域設置被啓用使用)進行更具體的比較適合在給定的地區進行分類。

7

這是一個按字母順序排列的比較(AI​​UI排序順序可能受當前語言環境的影響)。它比較每個字符串的第一個字符,如果左側的字符串具有更高的值,則爲真,如果降低則爲false;如果它們是相同的,那麼它的第二個字符,等等

這是一樣整數比較,比較了您使用[[ 2 -gt 1 ]]((2 > 1))。爲了說明字符串和整數比較之間的區別,考慮以下所有的都是「真」:

[[ 2 > 10 ]]  # because "2" comes before "1" in ASCII sort order 
[[ 10 -gt 2 ]] # because 10 is a larger number than 2 
((10 > 2))  # ditto 
1

是的,它比較ASCII值,如果相等,則重複下一個字符的比較。

/* Copyright (C) 1991, 1996, 1997, 2003 Free Software Foundation, Inc. 
    This file is part of the GNU C Library. 

    The GNU C Library is free software; you can redistribute it and/or 
    modify it under the terms of the GNU Lesser General Public 
    License as published by the Free Software Foundation; either 
    version 2.1 of the License, or (at your option) any later version. 

    The GNU C Library is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
    Lesser General Public License for more details. 

    You should have received a copy of the GNU Lesser General Public 
    License along with the GNU C Library; if not, write to the Free 
    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
    02111-1307 USA. */ 

#include <string.h> 
#include <memcopy.h> 

#undef strcmp 

/* Compare S1 and S2, returning less than, equal to or 
    greater than zero if S1 is lexicographically less than, 
    equal to or greater than S2. */ 
int 
strcmp (p1, p2) 
    const char *p1; 
    const char *p2; 
{ 
    register const unsigned char *s1 = (const unsigned char *) p1; 
    register const unsigned char *s2 = (const unsigned char *) p2; 
    unsigned reg_char c1, c2; 

    do 
    { 
     c1 = (unsigned char) *s1++; 
     c2 = (unsigned char) *s2++; 
     if (c1 == '\0') 
     return c1 - c2; 
    } 
    while (c1 == c2); 

    return c1 - c2; 
} 
+2

我不明白你爲什麼要粘貼一些與strcmp()無關的函數。 bash支持語言環境,在這種情況下,它使用'strcoll()'來執行適合特定字符集的比較。 – 2012-08-17 08:12:50

+0

您正確但strcmp以更簡單的形式說明了字符串比較。目的是展示如何比較一般字符串而不是特定的bash實現。這個方法在bash,python,perl,PHP,c,Java中是一樣的...... – olivecoder 2012-08-17 10:05:25

+0

更多...這個問題不是關於函數的名稱,而是關於方法。 – olivecoder 2012-08-17 10:12:46

相關問題