I had a need to do this in a bash-free way, and was surprised there's no utility (similar to env(1)
or sudo(1)
which runs a command in a modified working directory. So, I wrote a simple C program that does it:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
char ENV_PATH[8192] = "PWD=";
int main(int argc, char** argv) {
if(argc < 3) {
fprintf(stderr, "Usage: in <dir> <cmd> [<args>...]\n");
return 1;
}
if(chdir(argv[1])) {
fprintf(stderr, "Error setting working directory to \"%s\"\n", argv[1]);
return 2;
}
if(!getcwd(ENV_PATH + 4, 8192-4)) {
fprintf(stderr, "Error getting the full path to the working directory \"%s\"\n", argv[1]);
return 3;
}
if(putenv(ENV_PATH)) {
fprintf(stderr, "Error setting the environment variable \"%s\"\n", ENV_PATH);
return 4;
}
execvp(argv[2], argv+2);
}
The usage is like this:
$ in /path/to/directory command --key
~/.folder/command --key
? Does thecommand
require your current directory to be~/.folder
?git pull
require to change folder, so the question is useful. )