The shell is a tool for combining commands. Surely you already know the cd
command to change to a different directory, so what you're missing is a few pieces of glue to tie it together with another command.
You can run cd /some/dir && python foo.py
to change to a different directory and run a command there in one go. cd /some/dir; python foo.py
would work too; the advantage of using a double ampersand instead of a semicolon is that with &&
, the python
command is not executed if cd
fails (e.g. because you mistyped the directory name). You can chain more commands that way, e.g. cd /some/dir && python foo.py && make && make install
.
If you know in advance what commands you want to run in a different directory, you can run the cd
commands and those other commands in a subshell: if you write commands in parentheses, they are executed in a separate shell process that inherits all the state of the existing process (environment, current directory, etc.). Once the subshell terminates (at the closing parenthesis), the original shell resumes, unaffected by any changes inside the subshell.
(cd /some/dir && python foo.py && make && make install)
# back in the original directory
If you don't know in advance exactly what commands you're going to run, you can run cd
, then the other commands, and go back to the previous directory with cd -
.
cd /some/dir
python foo.py
make
make install
cd -
# back in the original directory
Unless you're using zsh as your shell, you can only go back once with cd -
. If you want to be able to go back further, use the commands pushd
and popd
. pushd /some/dir
works like cd /some/dir
, but it additionally adds the previous directory on top of a stack. popd
changes back to the directory saved at the top of the stack, and removes that directory from the stack. You can see the list of stacked directories with dirs
, and navigate to any of the directories on the stack with pushd -1
, pushd -2
, etc.
pushd /some/dir
python foo.py
make
make install
popd
# back in the original directory
A few commands have an option to tell them to work in a different directory. For example, make -C /some/dir
is equivalent to (cd /some/dir && make)
. This is mostly a typing shortcut or convenient when a shell isn't directly available; in general, you can always use cd
in the shell.
os.chdir()
or You can also set environment variables withos.environ
and useos.subprocess
oros.system
to execute make and make installmake -C /path/dir
and can you usecd /path/dir && make && cd -
orcd /path/dir ; make ; cd -
if you are not interested in catching errors