在bash中比较字符串

我们可以使用以下语法进行比较两个字符串。

$[ "apples" = "apples" ]
$echo $?
0

返回的值为0 表示字符串相同

$[ "apples" = "oranges" ]
$echo $?
1

返回1表示不等。

在脚本(if语句)中比较字符串

#!/bin/bash
string1="apples"
string2="oranges"
if [ "$string1" = "$string2" ]; then
	echo "The two strings are equal."
else
	echo "The two strings are not equal."
fi

可以使用!=运算符表示不相等:

#!/bin/bash
string1="apples"
string2="oranges"
if [ "$string1" != "$string2" ]; then
	echo "Strings are different."
else
	echo "Strings are not different."
fi

bash检查字符串是否为空 (字符串长度为0),使用“-Z”选项:

#!/bin/bash
string=""
if [[ -z $string ]]; then
	echo "The string is empty."
else
	echo "The string is not empty."
fi

bash检查字符串是否不为空,是-n选项

#!/bin/bash
string="hello"
if [[ -n $string ]]; then
    echo "The string is not empty."
else
    echo "The string is empty."
fi
日期:2020-07-07 20:54:33 来源:oir作者:oir