天天看點

Linux shell中比較操作符“==”與“-eq”對比

在linux shell程式設計中,經常會用到判斷字元串是否相等,可用于判斷字元串是否相等的操作符有‘-eq’(相等), ‘-ne’(不等于), ‘-lt’(小于), ‘-le’(小于或等于), ‘-gt’(大于)或‘-ge’(大于或等于),以及=,==,!=,<,>。

在bash指南中,字母操作符和符号操作符的兩端的參數英語表達式不相同,符号操作符用的是string,字母操作符用的是arg。

<code>string1==string2</code>

<code>string1=string2</code>

true if the strings are equal. ‘=’ should be used with the <code>test</code> command for posix conformance.

<code>string1!=string2</code>

true if the strings are not equal.

<code>string1&lt;string2</code>

true ifstring1sorts beforestring2lexicographically.

<code>string1&gt;string2</code>

true ifstring1sorts afterstring2lexicographically.

<code>arg1oparg2</code>

<code>op</code> is one of ‘-eq’, ‘-ne’, ‘-lt’, ‘-le’, ‘-gt’, or ‘-ge’. these arithmetic binary operators return true ifarg1is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal toarg2, respectively.arg1andarg2may be positive or negative integers.

在實際程式設計中發現,當用字母操作符,雖然效果與符号操作符相同,但會産生一個錯誤提示“[[: arg2: syntax error: operand expected (error token is "arg2")”。

如原文為

1

<code>[[ </code><code>"$1"</code> <code>-</code><code>eq</code> <code>""</code> <code>]] &amp;&amp; </code><code>echo</code> <code>"delete all spaces and comments of specialized file, using with $@ filename"</code> <code>&amp;&amp; </code><code>exit</code> <code>1</code>

修改為

<code>[[ </code><code>"$1"</code> <code>== </code><code>""</code> <code>]] &amp;&amp; </code><code>echo</code> <code>"delete all spaces and comments of specialized file, using with $@ filename"</code> <code>&amp;&amp; </code><code>exit</code> <code>1</code>

就不再提示了。

附帶一個實用小腳本,用途:grep掉空格和注釋符(#),簡單實用。

2

3

4

<code>#!/bin/bash   </code>

<code># delete all spaces and comments of specialized file, using with $@ filename    </code>

<code>[[ </code><code>"$1"</code> <code>== </code><code>""</code> <code>] &amp;&amp; </code><code>echo</code> <code>"delete all spaces and comments of specialized file, using with $@ filename"</code> <code>&amp;&amp; </code><code>exit</code> <code>1    </code>

<code>grep</code> <code>-</code><code>v</code> <code>\</code><code># $1 | grep -v ^$</code>

添加到作業系統中:

5

6

7

8

9

10

<code>cat</code> <code>&gt; delsc.sh &lt;&lt; eof   </code>

<code>#!/bin/bash    </code>

<code>[[ </code><code>"\$1"</code> <code>-== </code><code>""</code> <code>]] &amp;&amp; </code><code>echo</code> <code>"delete all spaces and comments of specialized file, using with \$@ filename"</code> <code>&amp;&amp; </code><code>exit</code> <code>1    </code>

<code>grep</code> <code>-</code><code>v</code> <code>\</code><code># \$1 | grep -v ^$    </code>

<code>eof    </code>

<code>chmod</code> <code>+x .</code><code>/delsc</code><code>.sh    </code>

<code>\</code><code>mv</code> <code>delsc.sh </code><code>/usr/local/bin/delsc</code>    

<code>which</code> <code>delsc    </code>

<code>cat</code> <code>/usr/local/bin/delsc</code>

用法:

<code>delsc filename</code>

繼續閱讀