[英]Getting the command line interpreter
My application takes a string command and repeatedly executes it during some process, each time with different environment variables. 我的应用程序接受一个字符串命令,并在某个过程中重复执行该命令,每次都使用不同的环境变量。 To support any kind of command, I run
cmd /C
with the command specified and the system takes care of parsing and running the command. 为了支持任何类型的命令,我使用指定的命令运行
cmd /C
,系统负责解析和运行该命令。 However, I think about making the application compatible with Unix .NET implementations by calling sh -c
instead on these systems. 但是,我考虑通过在这些系统上调用
sh -c
来使应用程序与Unix .NET实现兼容。
So, I want to determine two things in the most portable way - the proper interpreter that should be executed ( cmd
on Windows, sh
or possibly user-specified on Unix) and the style of variables which it accepts ( %var%
on Windows, $var
on Unix). 因此,我想以最可移植的方式确定两件事-应该执行的正确解释器(在Windows上为
cmd
,在Unix上为sh
或用户指定的用户指定),以及它接受的变量的样式(在Windows上为%var%
,在Unix上$var
)。
At the moment, I think about checking the COMSPEC
environment variable if it points to a Windows-style command-line interpreter and use that, or look for the SHELL
variable and use that. 目前,我考虑检查
COMSPEC
环境变量是否指向Windows样式的命令行解释器并使用它,或者查找SHELL
变量并使用它。 Is there a better managed alternative, or is this sufficient? 有没有更好管理的替代方法,或者这是否足够?
我可能在这里误解了一些东西,但是为什么不使用System.Environment.OSVersion.Platform
?
I have settled on checking the SHELL
and COMSPEC
environment variables to find the correct interpreter and its specification. 我已经确定要检查
SHELL
和COMSPEC
环境变量,以找到正确的解释器及其规范。
static void GetSystemShell(out bool comspec, out string fileName, out string arguments)
{
fileName = Environment.GetEnvironmentVariable("COMSPEC");
if(fileName != null)
{
comspec = true;
}else{
fileName = Environment.GetEnvironmentVariable("SHELL");
if(fileName != null)
{
comspec = false;
}else{
fileName = "cmd";
comspec = true;
}
}
if(comspec)
{
arguments = "/C";
}else{
arguments = "-c";
}
}
It prefers a COMSPEC
-compatible interpreter if both variables are set. 如果同时设置了两个变量,则它首选
COMSPEC
兼容的解释器。 There are also differences between how passing a command to the interpreter works, SHELL
expects the command as one (properly escaped) argument, while COMSPEC
works best simply by wrapping the command in additional quotes. 将命令传递到解释器的工作方式之间也存在差异,
SHELL
希望将命令作为一个(正确转义的)参数,而COMSPEC
只需将命令用附加引号引起来,则效果最佳。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.