How to compare strings in Bash

前端 未结 10 1763
眼角桃花
眼角桃花 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:35

    you can also use use case/esac

    case "$string" in
     "$pattern" ) echo "found";;
    esac
    
    0 讨论(0)
  • 2020-11-22 03:37

    Or, if you don't need else clause:

    [ "$x" == "valid" ] && echo "x has the value 'valid'"
    
    0 讨论(0)
  • 2020-11-22 03:41

    The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.

    Space in Bash is so much important. So the following will work:

    [ "$LINE" != "table_name" ] 
    

    But the following won't:

    ["$LINE" != "table_name"] 
    

    So please use as is:

    cat testonthis | while read LINE
    do
    if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
    echo $LINE
    fi
    done
    
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题