Search code examples
cshellgrepexecvpquotation-marks

execvp() with grep that has quotation marks


I did 'grep' in my own little shell. Other commands, like 'ls -al', 'pwd' ..etc, is working. But When I put 'grep', there was some problems.

char* f_grep[] = {"grep", "-n", "a", "a.txt", NULL};
char* s_grep[] = {"grep", "-n", "'a'", "a.txt", NULL};

execvp(f_grep[0], f_grep); // This works.

execvp(s_grep[0], s_grep); // This doesn't work.

I was wondering why I cannot use quotation marks with grep in execvp().

Thank you.


Solution

  • Normally, the shell removes one level of quotes from the command line arguments. So if you type,

    grep -n 'a' a.txt
    

    that's no different than

    grep -n a a.txt
    

    because the shell will remove the quotes.

    However, when you pass a string with quotes to execvp, the quotes will not be removed. Which means that the example with s_grep is the same as typing

    grep -n "'a'" a.txt
    

    The shell will remove the double quotes, and leave the single quotes, which is what's happening with execvp.


    If you want to experiment with this, you'll need two programs. The first program (called "showme") just echoes its command line arguments:

    // showme.c
    int main(int argc, char *argv[])
    {
        for (int i = 0; i < argc; i++)
            printf("%d: %s\n", i, argv[i]);
    }
    

    The second program calls execvp with some arguments for "showme":

    int main(void)
    {
        char *args[] = { "./showme", "a", "'b'", NULL };
        execvp(args[0], args);
    }
    

    The output:

    0: ./showme
    1: a
    2: 'b'