shell script 如何比字串大小 - Linux

Table of Contents

大家好:

最近在撰寫一個簡單的shell script時遇上一個有趣的問題
這隻shell script是利用bash執行的

功能很簡單:就是比較兩個字串的字典順序大小
經過man bash後得到訊息

string1 == string2
string1 = string2
True if the strings are equal. = should be used with the test
command for POSIX conformance.

string1 != string2
True if the strings are not equal.

string1 < string2
True if string1 sorts before string2 lexicographically.

string1 > string2
True if string1 sorts after string2 lexicographically.

於是我寫下類似以下的code
====
if [ "$str1" < "$str2"]; then
.....
else
....
fi
====
然而它總是在判斷上失敗,並且將 < 符號認定為 I/O redirect

請問是不是我會錯意或是使用錯誤了呢?

--

All Comments

Kyle avatarKyle2012-03-10
When used with [[, The < and > operators sort lexicogr
Anthony avatarAnthony2012-03-15
要用[[ ... ]]
Adele avatarAdele2012-03-15
謝謝樓上!解決了!(居然只是因為這樣 orz....)
Leila avatarLeila2012-03-19
[ ... ] 是sh compatible, [[ ... ]]則只有bash有
上次為了這兩個debug了一個小時....