Unix-string-operators

提供:Dev Guides
移動先:案内検索

Unix/Linux-シェル文字列演算子の例

次の文字列演算子は、Bourne Shellでサポートされています。

変数 a が「abc」を保持し、変数 b が「efg」を保持すると仮定します-

Operator Description Example
= Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a = $b ] is not true.
!= Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true. [ $a != $b ] is true.
-z Checks if the given string operand size is zero; if it is zero length, then it returns true. [ -z $a ] is not true.
-n Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true. [ -n $a ] is not false.
*str * Checks if* str* is not the empty string; if it is empty, then it returns false. [ $a ] is not false.

これは、すべての文字列演算子を使用する例です-

#!/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 ステートメントは、次の章で説明されている意思決定ステートメントです。