1

How to run a Linux shell command from a different directory without actually getting there?

In the following, I want to run a make command, but without getting into the source code directory, i.e., from my home directory:

me@mypc:~$ ~/my/source/code/directory/make  #This is wrong!

I have seen some examples which suggest as:

me@mypc:~$ cd ~/my/source/code/directory; make

But this ends up taking me into that source code directory, which I want to avoid.

There could the be the other option:

me@mypc:~$ cd ~/my/source/code/directory; make; cd ~

But it becomes complicated in cese.

I am wondering if there could be some way nicer and simpler than these?

3

4 Answers 4

8

You can try:

me@mypc:~$ (cd ~/my/source/code/directory; make)

Parentheses tell your shell to spawn a separate subshell, with its own current directory, and run the commands inside that subshell. After the command finishes, the subshell is closed, and you're back to your main shell, whose current directory never changed.

5

Do it in a subshell, e.g.

(cd ~/my/source/code/directory; make)

Alternately, you can use make's -C option, e.g.

make -C ~/my/source/code/directory
2
  • 2
    Beware that make -C is non portable as make implementations are not required (by POSIX) to support it, on the other hand (cd ...;make) is definitely portable
    – jlliagre
    Sep 21, 2014 at 12:11
  • Portability is more a concern for scripts, where the writer of the script is not necessarily the user of the script. For interactive use, it's a simple matter to use whatever technique is more convenient for whatever system you are on.
    – chepner
    Sep 22, 2014 at 4:35
3

You can also use

pushd ~/my/source/code/directory; make; popd

or

current=`pwd`; cd ~/my/source/code/directory; make; cd "$current"
0
$ (cd directory && make)

You need to use && instead of ;. Consider something like

cd junk && rm -rf *

With &&, bash will abort if the directory junk does not exist. If you try cd junk; rm -rf * and junk doesn’t exist, you’ll delete everything in the current directory :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.