How to compare strings in Bash

2018-12-31 19:30发布

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

标签: string bash
10条回答
高级女魔头
2楼-- · 2018-12-31 20:00

To compare strings with wildcards use

if [[ "$stringA" == *$stringB* ]]; then
  # Do something here
else
  # Do Something here
fi
查看更多
情到深处是孤独
3楼-- · 2018-12-31 20:01

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.)

查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 20:09

you can also use use case/esac

case "$string" in
 "$pattern" ) echo "found";;
esac
查看更多
几人难应
5楼-- · 2018-12-31 20:11

Using variables in if statements

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

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:

if [ = "valid" ]; then

Non-standard use of == operator

Note 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:

if [[ "$x" == "valid" ]]; then

or use the second case:

if [ "$x" = "valid" ]; then
查看更多
泛滥B
6楼-- · 2018-12-31 20:15

Or, if you don't need else clause:

[ "$x" == "valid" ] && echo "x has the value 'valid'"
查看更多
深知你不懂我心
7楼-- · 2018-12-31 20:15

I did it in this way that is compatible with bash, dash (sh):

testOutput="my test"
pattern="my"

case $testOutput in (*"$pattern"*)
    echo "if there is a match"
    exit 1
    ;;
(*)
   ! echo there is no coincidence!
;;esac
查看更多
登录 后发表回答