robins35
robins35

Reputation: 681

C UNIX Shell execvp Echoing Quotes

So I'm programming a basic UNIX minishell in C. Everything has been going smoothly, however I recently redid the way it parses arguments from the original string it gets from the console. Here's an example of the way it parses:

$> echo HELLO "" WORLD!
HELLO "" WORLD!

The argument array looks like this: [echo0, HELLO0, ""0, WORLD!0]

I pass it like so:

execvp(args[0], args);

However, echo is supposed to omit quotes, and as you can see it prints them out. Since echo isn't a builtin command in my case, I can't customize the way it prints. Does anybody know why this might be happening? I want to omit double quotes, but include every other sort of character(besides null of course). However the empty string counts as an argument itself, so:

echo HELLO "" WORLD!

should output:

HELLO  WORLD!

with 2 spaces in between, not:

HELLO WORLD!

with just one (since an empty string is an argument).

I hope this isn't too confusing. If you guys need any clarification, please just ask; I'd be happy to post code.

Upvotes: 0

Views: 1324

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 754490

#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    char *args1[] = { "/bin/echo", "HELLO", "\"\"", "WORLD!", 0 };
    char *args2[] = { "/bin/echo", "HELLO", "",     "WORLD!", 0 };
    if (fork() == 0)
    {
        execvp(args1[0], args1);
        exit(1);
    }
    while (wait(0) > 0)
        ;
    execvp(args2[0], args2);
    return(1);
}

This demonstrates the difference. There's no shell to interpret I/O redirection etc when you use execvp() — although in this case, execv() would do as well since I've specified the path for the echo command.

Upvotes: 1

epsalon
epsalon

Reputation: 2294

/bin/echo doesn't know about quotes. It simply prints all the arguments separated by spaces. The reason what you said works with a shell, is that the shell knows about quotes and passes an empty string as the second argument.

Upvotes: 1

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143229

It's shell that strips quotes when parsing the command line. If you pass them to exec* call directly, echo echoes them. It's then equivalent to echo HELLO '""' WORLD!.

Upvotes: 2

Related Questions