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?

tod
  • 1,539
  • 4
  • 17
  • 43
  • Possible duplicate of [How do I run a program with a different working directory from current, from Linux shell?](http://stackoverflow.com/questions/786376/how-do-i-run-a-program-with-a-different-working-directory-from-current-from-lin) – Madivad Feb 11 '16 at 13:26
  • @Madivad, Thanks for pointing. Great to know that, [though can't do](http://meta.stackoverflow.com/questions/265736/should-i-delete-my-question-if-it-is-marked-as-a-duplicate) nothing :|. – tod Feb 11 '16 at 15:52
  • That's cool. I didn't want it gone, just linked. – Madivad Feb 11 '16 at 21:21

4 Answers4

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.

liori
  • 40,917
  • 13
  • 78
  • 105
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
Hasturkun
  • 35,395
  • 6
  • 71
  • 104
  • 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 '14 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 '14 at 04:35
3

You can also use

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

or

current=`pwd`; cd ~/my/source/code/directory; make; cd "$current"
Bruce Barnett
  • 904
  • 5
  • 11
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 :(

andrewdotn
  • 32,721
  • 10
  • 101
  • 130