1

Script has to check if OLD_VERSION is not empty or if it doesn't match some pattern. I tried the below code

#!/bin/bash
OLD_VERSION="ABCDEFGHIJKL"
PATTERN="ABC"
if [[ ! "$OLD_VERSION" =~ "$PATTERN" ]] || [[ ! -z "$OLD_VERSION" ]];
then
    echo "Not matched or not null"
else
    echo "matched or null"
fi

For the above inputs :

 bash -x re.sh
 + OLD_VERSION=ABCDEFGHIJKL
 + PATTERN=ABC
 + [[ ! -z ABCDEFGHIJKL ]]
 + echo 'Not null or doesnot match'

I get the below output:

Not null or doesnot match

and also when I make old_version null, i get Not null or doesnot match, where i expect it to print null.

$OLD_VERSION=""

+ PATTERN=ABC
+ OLD_VERSION=
+ [[ ! -z '' ]]
+ [[ ! '' =~ ABC ]]
+ echo 'Not null or doesnot match'

I get wrong output. I am getting problem in or. What am I doing wrong?

UPDATE :

as suggested by sureshvv , i updated it like :

if [[ ! "$OLD_VERSION" =~ "$PATTERN"  && ! -z "${OLD_VERSION}" ]] ;
then
    echo "Not null or doesnot match"
else
    echo "matched or null"
fi

Thanks all.

3
  • 1
    define wrong output Commented Oct 19, 2015 at 7:52
  • question updated @amdixon Commented Oct 19, 2015 at 8:50
  • May be easier to read if you get rid of the double negative. So you can say if [ -z "$OLD_VERSION" || "$OLD_VERSION" =~ "$PATTERN" ]; then echo null or matched; fi Commented Oct 19, 2015 at 9:06

2 Answers 2

3

I think you want:

if [[ ! -z "$OLD_VERSION" && "$OLD_VERSION" =~ "$PATTERN" ]]; then
    echo Matched
else
    echo No match
fi
Sign up to request clarification or add additional context in comments.

3 Comments

thanks. But i got "matched" when i make old_version null
I got desired output when i changed it like " if [[ ! -z "$OLD_VERSION" && ! "$OLD_VERSION" =~ "$PATTERN" ]]; then "
check if you inverted the order ( answer is opposite echo order to yours )
-1

|| is handled by command [[, so you must put it inside [[ and ]]

if [[ ! "$OLD_VERSION" =~ "$PATTERN" || ! -z "$OLD_VERSION" ]];

1 Comment

Or it could be used as the bash command failure chain operator.

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.