简体   繁体   中英

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. However, I think about making the application compatible with Unix .NET implementations by calling sh -c instead on these systems.

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).

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. 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM