Check var for pattern

Problem

You want to check a variable for a given pattern.



Solution

This is my personal favorite way to check for values in vars. See examples.



Example


[[ $(echo $var | grep -ic "pattern") -eq 0 ]] &

You could also go for "-eq 1" – does contain:

[[ $(echo $var | grep -ic "pattern") -eq 1 ]] &

Or "-ne 0" for same, etc.

[[ $(echo $var | grep -ic "pattern") -ne 0 ]] &

Plus you could use || for "or" either in place of "&&" or after this block – same as if .. then "positive" else "negative" fi.

[[ $(echo $var | grep -ic "pattern") -eq 0 ]] || { echo "var does contain pattern" }



Reference

[tags], Unix Coding School[/tags]



Leave a Reply

Your email address will not be published. Required fields are marked *