Home > OS >  How to input command line arguments to a dotnet c# program using bash scripts?
How to input command line arguments to a dotnet c# program using bash scripts?

Time:05-24

I have a simple c# program that expects command line input (from Console.ReadLine()) when ran. There's a lot of inputs I have to provide, so I was wondering how I could automate this process. I currently have a shell script that attempts to do this, but it's not working.

#!/bin/sh
dotnet run #run the program
1          #input first argument (this failed so I tried echo 1 instead but no luck)
           # <- rest of command line inputs on each line

Not really familiar with shell scripts, and I'm not fixed on this solution if you had another solution in mind. My OS is MacOS.

CodePudding user response:

OK, so what I tried was this:

  1. I made a little mcve-Console App: (dotnet 6)
var input = Console.ReadLine();
while( !string.IsNullOrEmpty(input) )
{
    Console.WriteLine("User input: {0}", input);
    input = Console.ReadLine();
}
  1. Then I made a little input.txt
This is a Text.
This is another Text.
1
2
3
This is the final Text.
  1. and finally run.sh as follows:
#!/bin/sh
dotnet run < "input.txt"

Output was

User input: This is a Text.
User input: This is another Text.
User input: 1
User input: 2
User input: 3
User input: This is the final Text.

/bin/sh is linked to dash shell in my case.


If in run.sh you replace "input.txt" with "$1", then you can call it with ./run.sh whateveryourinputfileis.txt to make a little more flexible.

  • Related