1

I have a little problem with star character in my command for linux - I need to find out distro. When I replace this character witch e.g. 'fedora' then this command gives good results. In this case it write something like this: /bin/cat: /etc/*-release: Directory or file doesn't exist.

My code is:

    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "cat";
    p.StartInfo.Arguments = "/etc/*-release";
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();

Thanks in advance for your answer. Matej

matej148
  • 155
  • 1
  • 13

1 Answers1

3

When you run cat /etc/*-release from your shell, the shell is responsible for expanding the * to a list of matching files, if any.

When you directly execute a program yourself (as you're doing here with the Process interface), you need to re-create the shell's behavior yourself. This is actually for the best, as it is a bit silly to run cat to read a file from a full-featured programming language -- surely the language provides something easy for the logical equivalent of:

list = glob(/etc/*-release)
foreach file in (list):
    fd = open(file, "read");
    contents = read(fd)
    close(fd)
    dosomething_with(contents)

You can use whatever mechanism you like to replace the glob() bit there; a fellow stacker has provided his own glob() mechanism in another answer.

Community
  • 1
  • 1
sarnold
  • 102,305
  • 22
  • 181
  • 238
  • Thank you. Have you got some idea how can I run command like this: `iptables -L | grep Protect_blacklist | wc -l` ? I tried `p.StartInfo.FileName = "iptables"; p.StartInfo.Arguments = "-L | grep Protect_blacklist | wc -l";` but no success. Thanks in advance. – matej148 Apr 30 '12 at 00:13
  • Those `|` aren't arguments to the command; they are shell metacharacters. You might be able to use `sh -c "iptables -L | grep Protect_blacklist | wc -l"` in your commands, but it wouldn't be so bad to execute only `iptables -L` and then do the filtering and line counting internally to your programming language. (Either way would probably be fine.) – sarnold Apr 30 '12 at 00:19