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

may be it seems strange for you, but I want to run command in a specific folder without changing the current folder in the shell. Example - this is what I usually do:

~$ cd .folder
~/.folder$ command --key
~/.folder$ cd ..
~$ another_command --key

Though I want something like this:

~$ .folder command --key
~$ another_command --key

Is it possible?

2

4 Answers

If you want to avoid the second cd you can use

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

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

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

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
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like