简体   繁体   中英

Regex Comparison in Shell Script

In Xcode 8 I have a Run Script that is comparing a string to a regex:

if [ "$MOBILE_BUNDLE_IDENTIFIER" =~ ".+(Debug)" ]
then
RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Debug
elif [ "$MOBILE_BUNDLE_IDENTIFIER" =~ ".+(Test)" ]
then
RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Production
elif [ "$MOBILE_BUNDLE_IDENTIFIER" =~ ".+(ProductionTest)" ]
then
RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Test
else
RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Store
fi

The variable $MOBILE_BUNDLE_IDENTIFIER will be one of the following:

com.cnt.Filer
com.cnt.Filer.ProductionTest
com.cnt.Filer.Debug
com.cnt.Filer.Test

When I run this I get the following error:

line 4: [: =~: binary operator expected
line 7: [: =~: binary operator expected
line 10: [: =~: binary operator expected

In the full script lines 4, 7 and 10 are the then statements.

Does anyone know how I can successfully compare my variable to the regex?

  1. You should be using [[ string =~ regex ]] for regex in BASH
  2. Don't quote regex
  3. Looks like you don't even need regex, you can just do string comparison using ==

Your script can be this:

if [[ $MOBILE_BUNDLE_IDENTIFIER == *Debug* ]]; then
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Debug
elif [[ $MOBILE_BUNDLE_IDENTIFIER == *Test* ]]; then
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Production
elif [[ $MOBILE_BUNDLE_IDENTIFIER == *ProductionTest* ]]; then
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Test
else
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Store
fi

PS: You may also consider using case

case "$MOBILE_BUNDLE_IDENTIFIER" in
*Debug*)
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Debug
   ;;
*Test*)
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Production
   ;;
*ProductionTest*)
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Test
   ;;
*)
   RESOURCE_PATH=${SRCROOT}/Resources/Clients/Cnt/Files/Store
   ;;
esac

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM