Requirements: Yesterday, I read an article published by Team Zhang in the blog garden, and I don't need to create a project C# single file that can be executed directly. When we perform some tasks under Linux, we may need to write shell scripts, for people who do not understand shell language, it is impossible to write or have learning costs, if you know C# language, you can now write a script through Shebang format and execute it on the Linux server.
Linux Shebang
A shebang (also known as hashbang or pound-bang) is a sequence of characters (#!) consisting of a hash (#) and an exclamation mark (!) that appears on the first line of a script file in a Unix-like operating system. Shebang is used to specify the interpreter that executes the script. When a script file is executed, the operating system looks for the first line of the file, and if it finds a shebang, it uses the specified interpreter to run the script.
Some typical shebang interpreter instructions are listed below:
What is dotnet run app.cs?
A new feature in .NET 10 Preview 4 that makes getting started with C# easier than ever. Now you can run C# files directly using dotnet run app.cs. This means you don't need to create project files or build a framework for your entire application to run quick scripts, test code snippets, or experiment with an idea. It's simple, intuitive, and designed to simplify the C# development experience, especially for developers just starting out. Previously, this gap was filled by third-party developers (e.g., cs-script, dotnet-script, etc.).
Until now, executing C# code with dotnetCLI required a project structure that contained the file .csproj. With this new feature (we call it a file-based app), you can run standalone files directly .cs as you would with a scripting language like Python or JavaScript.
Remark:File-based apps still require the .NET SDK to useBecause they are still built using a regular MSBuild-based system. If you wish to run a file-based application using "dotnet run app.cs", then.NET SDK is required。
Write C# scripts on Linux
This article uses a Rocky Linux 9 system to test, first download .NET 10 SDK preview.5 to the system with the following command:
As shown below:
Simple code
Write a hello.cs script with the following code:
Grant execution permissions, and execute the command as follows:
The output is as follows:
Dependent on nuget package code
Often the logic is more complex, we may need to introduce a third-party nuget package, call the functions in it to complete our needs, you can use the #:p ackage command to introduce the nuget package, toNewtonsoft.JsonFor example, the code is as follows:
The output is as follows:
Reference:
The hyperlink login is visible.
The hyperlink login is visible. |