Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access command line arguments in .csx script?

I'm using csi.exe the C# Interactive Compiler to run a .csx script. How can I access any command line arguments supplied to my script?

csi script.csx 2000

If you're not familiar with csi.exe, here's the usage message:

>csi /?
Microsoft (R) Visual C# Interactive Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

Usage: csi [option] ... [script-file.csx] [script-argument] ...

Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop).
like image 529
Colonel Panic Avatar asked Jul 22 '16 14:07

Colonel Panic


People also ask

What are command-line arguments in Bash?

Command-Line Arguments are parameters that are specified with the filename of the bash script at the time of execution. The command-line arguments allow the script to perform dynamic actions based on the input: To pass a parameter to a bash script just write it after the name of the bash script in the terminal:

How do I read a command line argument in a script?

Method Two: Read Command-Line Argument with for Loop Another way to check command-line arguments in a bash script is by referencing a special bash parameter called $@, which expands to a list of supplied command-line arguments. Since $@ is an iterable list, you can use for loop to read each argument in the list.

How to pass or access command-line arguments in C#?

How to Pass or Access Command-line Arguments in C#? In C#, the Main () method is an entry point of the Console, Windows, or Web application (.NET Core). It can have a string [] args parameter that can be used to retrieve the arguments passed while running the application.

Where are the arguments stored in a shell script?

The locations at the command prompt of the arguments as well as the location of the command, or the script itself, are stored in corresponding variables. These variables are special shell variables.


1 Answers

CSI has an Args global which parses out the arguments for you. For most cases, this will get you the arguments you wanted as if you were accessing argv in a C/C++ program or args in the C# Main() signature static void Main(string[] args).

Args has a type of IList<string> rather than string[]. So you will use .Count to find the number of arguments instead of .Length.

Here is some example usage:

#!/usr/bin/env csi
Console.WriteLine($"There are {Args.Count} args: {string.Join(", ", Args.Select(arg => $"“{arg}”"))}");

And some example invocations:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx
There are 0 args:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx hi, these are args.
There are 4 args: “hi,”, “these”, “are”, “args.”

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx 'hi, this is one arg.'
There are 1 args: “hi, this is one arg.”
like image 113
binki Avatar answered Oct 08 '22 10:10

binki