如何在 Bash 中比较字符串

如何将变量与字符串进行比较(如果匹配则执行某些操作)?

答案

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi
if [ = "valid" ]; then
if [[ "$x" == "valid" ]]; then
if [ "$x" = "valid" ]; then
[ "$x" == "valid" ] && echo "x has the value 'valid'"
a="abc"
b="def"

# Equality Comparison
if [ "$a" == "$b" ]; then
    echo "Strings match"
else
    echo "Strings don't match"
fi

# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
    echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
    echo "$b is lexicographically smaller than $a"
else
    echo "Strings are equal"
fi
if [[ "$stringA" == *$stringB* ]]; then
  # Do something here
else
  # Do Something here
fi
[ "$x" == "valid" ] && echo "valid" || echo "invalid"
[ "$x" == "valid" ] && echo "valid" || echo "invalid"
(
[ "$x" == "valid" ] 
&&
echo "valid"
)
||
echo "invalid"
case "$string" in
 "$pattern" ) echo "found";;
esac
[ "$LINE" != "table_name" ]
["$LINE" != "table_name"]
cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done
if [[ "${ACTION,,}" =~ ^(start|stop)$ ]]; then
  echo "valid action"
fi
if [[ "${str,,}" == *"yes"* ]] ;then
if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
if [[ "${str}" == *"yes"* ]] ;then
if [[ "${str}" =~ "yes" ]] ;then
if [[ "${str}" == "yes" ]] ;then
if [[ "${str,,}" == "yes" ]] ;then
if [ "$a" = "$b" ] ;then
testOutput="my test"
pattern="my"

case $testOutput in (*"$pattern"*)
    echo "if there is a match"
    exit 1
    ;;
(*)
   ! echo there is no coincidence!
;;esac