How to compare strings in Bash

前端 未结 10 1857
眼角桃花
眼角桃花 2020-11-22 02:48

How do I compare a variable to a string (and do something if they match)?

10条回答
  •  滥情空心
    2020-11-22 03:42

    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
    

    Notes:

    1. Spaces between if and [ and ] are important
    2. > and < are redirection operators so escape it with \> and \< respectively for strings.

提交回复
热议问题