Search code examples
c#linux.net-coremsbuildcross-platform

dotnet Linux build fails because project has build events written for cmd


I'm trying to build a .Net project - that was created on Windows - using the Linux dotnet-core SDK (8.0.404), but the build fails because the project has pre/post build events that are written in Windows cmd.exe ("batch scripting") syntax:

$ dotnet build Project
  Determining projects to restore...
  All projects are up-to-date for restore.
  /usr/bin/sh: 3: /tmp/MSBuildTempodeda/tmp6707ffb923be418d8a5720ef9ed70268.exec.cmd: Syntax error:
    "(" unexpected (expecting "then")
/snap/dotnet-sdk/254/sdk/8.0.404/Microsoft.Common.CurrentVersion.targets(1426,5): error MSB3073:
    The command " [/home/odeda/path/to/project/Project.csproj]
/snap/dotnet-sdk/254/sdk/8.0.404/Microsoft.Common.CurrentVersion.targets(1426,5): error MSB3073:
             SOME BATCH SYNTAX WITH IF CLAUSES [/home/odeda/path/to/project/Project.csproj]
/snap/dotnet-sdk/254/sdk/8.0.404/Microsoft.Common.CurrentVersion.targets(1426,5): error MSB3073:
    " exited with code 2. [/home/odeda/path/to/project/Project.csproj]

Build FAILED.

the .Net SDK obviously tries to run the build events - that were created to run on the local Windows "system shell" - with the Linux POSIX shell, which as expected doesn't work (its not even close to being a similar syntax, which is yet another reason Microsoft's claim of Windows POSIX compatibility is a lie).

Is there a way to set up different build event scripts to be run on Windows vs. Linux? I didn't find anything appropriate in the MSBuild documentation.


Solution

  • You can add a Condition attribute to the Exec item to determine the current OS. On Windows, the value of the $(OS) variable is Windows_NT, while on Linux it is Unix (I tested on Ubuntu, if this value doesn't match, try to execute echo $(OS) without a condition).

    <Target Name="PostBuild" AfterTargets="PostBuildEvent">
        <Exec Command="echo !!!!Windows!!!!" Condition="'$(OS)'=='Windows_NT'" />
        <Exec Command="echo !!!!Unix!!!!" Condition="'$(OS)'=='Unix'" />
    </Target>