How to compare strings in Bash

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

    I have to disagree one of the comments in one point:

    [ "$x" == "valid" ] && echo "valid" || echo "invalid"
    

    No, that is not a crazy oneliner

    It's just it looks like one to, hmm, the uninitiated...

    It uses common patterns as a language, in a way;

    And after you learned the language.

    Actually, it's nice to read

    It is a simple logical expression, with one special part: lazy evaluation of the logic operators.

    [ "$x" == "valid" ] && echo "valid" || echo "invalid"
    

    Each part is a logical expression; the first may be true or false, the other two are always true.

    (
    [ "$x" == "valid" ] 
    &&
    echo "valid"
    )
    ||
    echo "invalid"
    

    Now, when it is evaluated, the first is checked. If it is false, than the second operand of the logic and && after it is not relevant. The first is not true, so it can not be the first and the second be true, anyway.
    Now, in this case is the the first side of the logic or || false, but it could be true if the other side - the third part - is true.

    So the third part will be evaluated - mainly writing the message as a side effect. (It has the result 0 for true, which we do not use here)

    The other cases are similar, but simpler - and - I promise! are - can be - easy to read!
    (I don't have one, but I think being a UNIX veteran with grey beard helps a lot with this.)

提交回复
热议问题