1

I want to test if the $ip is equal to one of the two values: "a" or "b". When I test against only "a" it works. I didn`t want to do || and perform another grep+cut, since I have done those once, I would like to take the result and test it against these 2 values.

if [[ $(grep -e "$ip" FILE |cut -d' ' -f5) =~ 'a\|b'; then
 echo "OK"
fi
3
  • 1
    Could you add the language in the question tags as this is obviously not language-agnostic? Commented Mar 14, 2016 at 15:13
  • added linux, bash and unix Commented Mar 14, 2016 at 15:15
  • remove the backslash and quotes on the match part Commented Mar 14, 2016 at 15:25

2 Answers 2

3

You don't have to do another grep+cut, you can always assign the result to a variable. Regex match is not equivalent to equality check. The following will be more readable

var=...; if [[ "$var" = "a" || "$var" = "b" ]]; then echo OK; fi
Sign up to request clarification or add additional context in comments.

2 Comments

You can also use [[ $var = @(a|b) ]]; versions of bash prior to 4.1 will require running shopt -s extglob first to allow the extended pattern syntax.
didn't know this thanks, actually better to convey intention.
0

A case statement is a readable alternative

case "$(grep ...)" in
    a|b) 
        echo OK
        ;;
    *)
        echo not OK
        ;;
esac    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.