Change Working Directory In Shell With A Python Script


Answer :

Others have pointed out that you can't change the working directory of a parent from a child.

But there is a way you can achieve your goal -- if you cd from a shell function, it can change the working dir. Add this to your ~/.bashrc:

go() {     cd "$(python /path/to/cd.py "$1")" } 

Your script should print the path to the directory that you want to change to. For example, this could be your cd.py:

#!/usr/bin/python import sys, os.path if sys.argv[1] == 'tdi': print(os.path.expanduser('~/long/tedious/path/to/tdi')) elif sys.argv[1] == 'xyz':  print(os.path.expanduser('~/long/tedious/path/to/xyz')) 

Then you can do:

tdi@bayes:/home/$> go tdi tdi@bayes:/home/tdi$> go tdi 

That is not going to be possible.

Your script runs in a sub-shell spawned by the parent shell where the command was issued.

Any cding done in the sub-shell does not affect the parent shell.


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?