developer9969
developer9969

Reputation: 5236

replace string in class bash and azuredevops (ios xamarin pipeline)

I am trying to write a bash script to change a string in a class for my azure devops pipeline.But cannot make it work.

Copied the script from https://github.com/Microsoft/appcenter-build-scripts-examples/blob/master/xamarin/app-constants/appcenter-pre-build.sh

my bash attempt:

  1. Added a bash task (inline script)
  2. Created an env variable API_URL with value ="https://production.com/api"
  3. My Class to change

    namespace Core
    {
       public class AppConstant
       {
         public const string ApiUrl = "https://production.com/api";
         public const string AnotherOne="AAA";
       }
    }        
    

My script

    if [ ! -n "$API_URL" ]
    then
        echo "You need define the API_URL variable"
        exit
    fi

    APP_CONSTANT_FILE=$(Build.SourcesDirectory)/MyProject/Core/AppConstant.cs

    if [ -e "$APP_CONSTANT_FILE" ]
    then
        echo "Updating ApiUrl to $API_URL in AppConstant.cs"
        sed -i '' 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

        echo "File content:"
        cat $APP_CONSTANT_FILE
    fi

why does my variable not change? many thanks

Upvotes: 3

Views: 2000

Answers (1)

Kubator
Kubator

Reputation: 1383

Your script is correct and will get desired output, only remove the dual apostrophes after sed -i:

sed -i 's#ApiUrl = "[a-z:./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

However I would also change regexp at least to this, since . (dot) is reserved as any character in regexp:

sed -i 's#ApiUrl = "[a-z:\./]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

Or even to this (in order to take whatever characters between quotes):

sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

Test:

$ cat > developer9969.txt
namespace Core
{
   public class AppConstant
   {
     public const string ApiUrl = "https://production.com/api";
   }
}

API_URL='https://kubator.com/'
APP_CONSTANT_FILE='./developer9969.txt'
sed -i 's#ApiUrl = "[^"]*"#ApiUrl = "'$API_URL'"#' $APP_CONSTANT_FILE

$ cat $APP_CONSTANT_FILE
namespace Core
{
   public class AppConstant
   {
     public const string ApiUrl = "https://kubator.com/";
   }
}

Upvotes: 5

Related Questions