cshellcommandexecpwd

How do I execute a Shell built-in command with a C function?


I would like to execute the Linux command "pwd" through a C language function like execv().

The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.


Solution

  • You should execute sh -c echo $PWD; generally sh -c will execute shell commands.

    (In fact, system(foo) is defined as execl("sh", "sh", "-c", foo, NULL) and thus works for shell built-ins.)

    If you just want the value of PWD, use getenv, though.