How can I run command in a folder without changing my current directory to it?

Solution 1:

If you want to avoid the second cd you can use

(cd .folder && command --key)
another_command --key

Solution 2:

Without cd... Not even once. I found two ways:

# Save where you are and cd to other dir
pushd .folder
command --key
# Get back where you were at the beginning.
popd
another_command --key

and second:

find . -maxdepth 1 -type d -name ".folder" -execdir command --key \;
another_command --key

Solution 3:

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

Solution 4:

A simple bash function for running a command in specific directory:

# Run a command in specific directory
run_within_dir() {
    target_dir="$1"
    previous_dir=$(pwd)
    shift
    cd $target_dir && "$@"
    cd $previous_dir
}

Usage:

$ cd ~
$ run_within_dir /tmp ls -l  # change into `/tmp` dir before running `ls -al`
$ pwd  # still at home dir