Ruari Bush
Ruari Bush

Reputation: 1

I'm trying to perform two string comparisons with an "if" and an "OR"

I'm new to bash and I am trying to do two string comparisons with an or statement. Can anyone give me any idea where I have gone wrong?

    echo $DEVICETYPE
    FILEHEADER=ANDROID
    if [[ "$DEVICETYPE" == "iPad" ] || ["$DEVICETYPE" == "iPhone" ]];
        then
            $FILEHEADER = IOS
    fi
    echo $FILEHEADER

iPad

ANDROID

Upvotes: 0

Views: 68

Answers (1)

Michael Petch
Michael Petch

Reputation: 47593

As others have mentioned I should point this out for completeness. The statement:

echo $FILEHEADER = IOS

will simply print out the contents of FILEHEADER variable followd by = IOS . This won't do assignment. Assignment is done as follows with name of variable without the $ followed by what you wish to assign to it. Note there are no spaces around the =. In your example it should have been:

FILEHEADER=IOS

Regarding the expressions your code:

if [[ "$DEVICETYPE" == "iPad" ] || ["$DEVICETYPE" == "iPhone" ]];

could be replaced with:

if [ "$DEVICETYPE" == "iPad" ] || [ "$DEVICETYPE" == "iPhone" ];

You need to remove the outer brackets. As well there is a subtle change that has to be made. You had ["$DEVICETYPE" you need to add a space after the [ so it became [ "$DEVICETYPE". If you want to group logical expressions then you could use parentheses so it could have been written this way (although it doesn't change this examples semantics):

if ([ "$DEVICETYPE" == "iPad" ] || [ "$DEVICETYPE" == "iPhone" ]);

If you are only targeting bash then the following may have been the more natural wayto express it. Unfortunately this form may not work in other shells (it is less portable):

if [[ $DEVICETYPE == "iPad" || $DEVICETYPE == "iPhone" ]];

If you are concerned about operator precedence you could always clarify it with:

if [[ ($DEVICETYPE == "iPad") || ($DEVICETYPE == "iPhone") ]];

Although not asked but may be of value is to realize that one can use a wildcard asterisk(*) to check for anything that starts with iPhone or iPad as in this example:

if [[ ($DEVICETYPE == "iPad"*) || ($DEVICETYPE == "iPhone"*) ]];

So if DEVICETYPE is iPhone 2 or iPhone2 or iPad Mini then they would all match as well. The asterisk says match any other characters.

Upvotes: 2

Related Questions