.NET CLI Shebangs and Argument Parsing
I’ve been using the dotnet run app.cs CLI applications for a little while. Until now, I had no problem with arguments passed in, but today I added a -v option to my application to print out the version number.
Something like this -
#!/usr/bin/dotnet run
foreach (string arg in args)
{
switch (arg)
{
case "-v":
case "--version":
Console.WriteLine("Simple Application: Version 1.0.0");
return;
}
} When I run it with ./app.cs --version it works fine, but when I run it with ./app.cs -v I get an error -
Required argument missing for option: '-v'.
Description:
.NET Run Command
Usage:
dotnet run [<applicationArguments>...] [options]
//snip
-v, -verbosity <LEVEL> Set the MSBuild verbosity level. Allowed values are q[uiet],
m[inimal], n[ormal], d[etailed], and diag[nostic].For some reason, the dotnet run command is treating -v as an option for itself, rather than passing it through to the application. That is why it complains about a required argument missing for the -v option, which relates to verbosity in dotnet run.
If I run it with ./app.cs -- -v it is fine again, but I don’t want to have to do that every time.
I tried changing the shebang and found some that work and some that don’t.
Here are the ones that work -
1#!/usr/bin/dotnet --
2#!/usr/bin/env -S dotnet --
3#!/usr/bin/env -S dotnet run --There, hope this helps someone or future me.