shell 字符串 比较
在Shell脚本中,可以使用条件表达式和测试命令来比较字符串。以下是一些常见的字符串比较示例:
str1="Hello"
str2="World"
# 检查两个字符串是否相等
if [ "$str1" = "$str2" ]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
# 检查两个字符串是否不等
if [ "$str1" != "$str2" ]; then
echo "Strings are not equal."
else
echo "Strings are equal."
fi
# 检查字符串是否为空
if [ -z "$str1" ]; then
echo "str1 is empty."
else
echo "str1 is not empty."
fi
# 检查字符串是否非空
if [ -n "$str1" ]; then
echo "str1 is not empty."
else
echo "str1 is empty."
fi
# 字符串排序比较(仅限ASCII字符)
if [[ "$str1" < "$str2" ]]; then
echo "str1 comes before str2."
else
echo "str1 does not come before str2."
fi
# 注意:使用[[ ]] 比使用[ ] 更加灵活,因为它支持更多的比较操作和模式匹配。
请根据实际需求选择合适的比较方式。注意,在进行字符串比较时,推荐使用双括号 [[ ]] 来避免某些潜在的问题,特别是在处理含有空格的字符串时。