Shell 字符串運算範例

下面是一個例子,它使用的所有字符串運算:

#!/bin/sh a="abc" b="efg" if [ $a = $b ] then echo "$a = $b : a is equal to b" else echo "$a = $b: a is not equal to b" fi if [ $a != $b ] then echo "$a != $b : a is not equal to b" else echo "$a != $b: a is equal to b" fi if [ -z $a ] then echo "-z $a : string length is zero" else echo "-z $a : string length is not zero" fi if [ -n $a ] then echo "-n $a : string length is not zero" else echo "-n $a : string length is zero" fi if [ $a ] then echo "$a : string is not empty" else echo "$a : string is empty" fi

這將產生以下輸出結果:

abc = efg: a is not equal to b
abc != efg : a is not equal to b -z abc : string length is not zero -n abc : string length is not zero
abc : string is not empty

要注意以下幾點:

  • 運算符和表達式之間必須有空格,例如2+2是不正確的,因爲它應該寫成2 + 2.

  • if...then...else...fi 語句在下一章節中已經解釋的決策聲明。