1

What's the difference between "sh -c cmd" and "cmd", when executed from a shell commnad line, and when executed from a c exec() function, respectively? Thanks.

2 Answers 2

4

It depends on what 'cmd' represents. In the basic case where it is a simple command name (say ps or ls), then there is no difference at the shell command line, and precious little difference when executed by execvp(). The 'non-p' exec*() functions do have slightly different semantics; they don't use the PATH variable, so the command must exist and be executable in the current directory or it will fail.

However, if cmd is more complex, then it can make a big difference. For example:

$ echo $$ 17429 $ sh -c 'echo $$' 76322 $ sh -c "echo $$" 17429 $ 

The first reports the process ID of the original shell; the second reports the process ID of the shell run as sh; the third is an expensive way of reporting the process ID of the original shell. Note that the single quotes vs double quotes are significant too. Here, the quotes would not be present in the C invocation (the shell removes the quotes from around the arguments), and the value of $$ would be that of the child shell:

char *argv[] = { "sh", "-c", "echo $$", 0 }; execvp(argv[0], argv); 

(I said the quotes are not present in the C invocation; they are needed around the string in the C code, but the value passed to sh doesn't contain any quotes — so I meant what I said, though it might not be quite as blindingly obvious as all that.)

Sign up to request clarification or add additional context in comments.

2 Comments

Another example is cd vs sh -c cd. The first changes the current directory to home, while the second does nothing.
@tom: indeed, with the added complication that there is no cd binary for the exec*() functions to execute at all. Similar comments apply to other shell built-in functions — exit, jobs, ...
0

From the man page:

-c string If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

Just cmd will run through bash (or whatever your default) shell is. You need the sh to explicitly call -c argument.

exec shouldn't make a difference here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.