How do I compare a variable to a string (and do something if they match)?
相关问题
- how to split a list into a given number of sub-lis
- Generate string from integer with arbitrary base i
- JQ: Select when attribute value exists in a bash a
- Converting a string array to a byte array
- bash print whole line after splitting line with if
相关文章
- JSP String formatting Truncate
- Check if directory exists on remote machine with s
- Selecting only the first few characters in a strin
- Python: print in two columns
- Reverse four length of letters with sed in unix
- Launch interactive SSH bash session from PHP
- extending c++ string member functions
- Google app engine datastore string encoding proble
To compare strings with wildcards use
I have to disagree one of the comments in one point:
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.
Each part is a logical expression; the first may be true or false, the other two are always true.
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.)
you can also use use case/esac
Using variables in if statements
If you want to do something when they don't match, replace
=
with!=
. You can read more about string operations and arithmetic operations in their respective documentation.Why do we use quotes around
$x
?You want the quotes around
$x
, because if it is empty, your bash script encounters a syntax error as seen below:Non-standard use of
==
operatorNote that
bash
allows==
to be used for equality with[
, but this is not standard.Use either the first case wherein the quotes around
$x
are optional:or use the second case:
Or, if you don't need else clause:
I did it in this way that is compatible with bash, dash (sh):