一、什麼是Shell
Shell是一種解釋型語言,常見的有Bash、Zsh、Ksh等,主要運行於Unix/Linux系統中,也有一些支持Windows平台。
Shell腳本可以運行一系列的命令,也可以用於編寫一些簡單的程序。
二、字符串比較
Shell中判斷字符串是否相等可以使用”=”、”==”或”eq”運算符。例如:
if [ "$str1" = "$str2" ]; then echo "str1 equals to str2" fi if [ "$str1" == "$str2" ]; then echo "str1 equals to str2" fi if [ "$str1" eq "$str2" ]; then echo "str1 equals to str2" fi
注意:變量的值需要用雙引號括起來,否則當變量的值為空時,會報錯。
在判斷字符串是否不相等時,可以使用”!=”、”ne”運算符。
if [ "$str1" != "$str2" ]; then echo "str1 is not equal to str2" fi if [ "$str1" ne "$str2" ]; then echo "str1 is not equal to str2" fi
三、子串包含判斷
判斷一個字符串是否包含另一個字符串,可以使用”=”、”==”、”!=”、”!=”運算符配合通配符”*”。例如:
if [ "$str1" = *"hello"* ]; then echo "str1 contains hello" fi if [ "$str1" == *"hello"* ]; then echo "str1 contains hello" fi if [ "$str1" != *"world"* ]; then echo "str1 does not contain world" fi if [ "$str1" != *"world"* ]; then echo "str1 does not contain world" fi
注意:通配符”*”表示任意字符串,可以放在匹配字符串的前面或後面,但是需要用雙引號括起來,否則當變量的值為空時,會報錯。
四、小結
在Shell中判斷字符串是否相等和包含,可以使用”=”、”==”、”eq”、”!=”、”ne”運算符配合雙引號和通配符”*”來實現,同時需要注意雙引號的使用和空字符串的判斷。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/270324.html