Bash字串

在本小節中,我們將學習有關bash字串及其運算符的使用。

與其他編程語言一樣,Bash字串是一種數據類型,例如整數或浮點。它用於表示文本而不是數字。它是一組可能還包含數字的字元的組合。

例如,單詞zaixian和短語Welcome to zaixian都是字串。如果正確指定,甚至像01234也可以視為字串。要求程式員將字串括在引號中,以便Bash將數據視為字串,而不是數字,變數名或數組等之類的。

Bash由執行字串操作和操作它們的多種方式組成。以下是Shell腳本中用於執行字串操作的一些運算符:

1. 等於運算符

等於運算符(=)用於檢查兩個字串是否相等。

語法

Operand1 = Operand2

示例

#!/bin/bash
#Script to check whether two strings are equal.

str1="xntutor.com"
str2="xuhuhu.com"

if [ $str1 = $str2 ];
then
echo "Both the strings are equal."
else
echo "Strings are not equal."
fi

執行上面示例代碼,得到以下結果:

Strings are not equal.

2. 不等於運算符

不等於運算符(!=)用於定義字串不相等。

語法

Operand1 != Operand2

示例

#!/bin/bash
#Script to check whether two strings are equal.

str1="xuhuhu.com"
str2="xntutor.com"

if [[ $str1 != $str2 ]];
then
echo "Strings are not equal."
else
echo "Strings are equal."
fi

執行上面示例代碼,得到以下結果:

Strings are not equal.

3. 小於運算符

“小於運算符(\<)”是一個條件運算符,用於檢查string1是否小於string2

語法

Operand1 \< Operand2

示例

#!/bin/sh

str1="xuhuhu.com"
str2="xntutor.com"
if [ $str1 \< $str2 ];
then
    echo "$str1 is less then $str2"
else
    echo "$str1 is not less then $str2"
fi

執行上面示例代碼,得到以下結果:

xuhuhu.com is not less than xntutor.com

4. 大於運算符

“大於運算符(\>)”用於檢查string1是否大於string2

語法

Operand1 \> Operand2

示例

#!/bin/sh

str1="xntutor.com"
str2="xuhuhu.com"
if [ $str1 \> $str2 ];
then
    echo "$str1 is greater then $str2"
else
    echo "$str1 is less then $str2"
fi

執行上面示例代碼,得到以下結果:

xntutor.com is greater then xuhuhu.com

5. 檢查字串長度是否大於零

下麵運算符-n用於檢查字串是零還是大於零。

語法

[ -n Operand ]

示例

#!/bin/sh

str="Welcometozaixian"

if [ -n $str ];
then
    echo "String is not empty"
else
    echo "String is empty"
fi

執行上面示例代碼,得到以下結果:

String is not empty

6. 檢查字串長度是否等於零

此運算符用於檢查字串是否為空或等於零。

語法

[ -z Operand ]

示例

#!/bin/sh

str=""

if [ -z $str ];
then
    echo "String is empty."
else
    echo "String is non-empty."
fi

執行上面示例代碼,得到以下結果:

String is empty

上一篇: Bash until迴圈 下一篇: Bash查找字串