Junius L
Junius L

Reputation: 16122

execve with sed fails

I'm creating a small unix shell, execve has an issue with sed. When I execute sed -e 's/Roses/Turnips/' the command fails with execve.

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

int main(int ac, char **av, char **envp)
{
    char *argv[] = { "/usr/bin/sed", "-e", "'s/Roses/Turnips/'", 0 };
    execve(argv[0], &argv[0], envp);
    fprintf(stderr, "Failed!\n");
    return -1;
}

Error:

/usr/bin/sed: -e expression #1, char 1: unknown command: `''

Upvotes: 0

Views: 254

Answers (2)

Barmar
Barmar

Reputation: 780899

Get rid of the single quotes around the s/// argument. Those are part of shell syntax, not sed syntax.

char *argv[] = { "/usr/bin/sed", "-e", "s/Roses/Turnips/", 0 };

execve executes the program directly, it doesn't use a shell. Every argument is sent literally to the program, so no escaping or quoting is needed as when running a program in the shell.

Upvotes: 2

Petr Skocik
Petr Skocik

Reputation: 60058

That problem arises inside of sed because it doesn't want your single quotes. You'd use those single quotes in a shell to prevent it from interpreting the sed command, but the shell would ultimately remove those quotes, which is what you need to do also.

Upvotes: 0

Related Questions