I want to implement a userland command that will take one of its arguments (path) and change the directory to that dir. After the program completion I would like the shell to be in that directory. So I want to implement cd
command, but with external program.
Can it be done in a python script or I have to write bash wrapper?
Example:
JavaScript
x
3
1
tdi@bayes:/home/$>python cd.py tdi
2
tdi@bayes:/home/tdi$>
3
Advertisement
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:
JavaScript
1
4
1
go() {
2
cd "$(python /path/to/cd.py "$1")"
3
}
4
Your script should print the path to the directory that you want to change to. For example, this could be your cd.py:
JavaScript
1
5
1
#!/usr/bin/python
2
import sys, os.path
3
if sys.argv[1] == 'tdi': print(os.path.expanduser('~/long/tedious/path/to/tdi'))
4
elif sys.argv[1] == 'xyz': print(os.path.expanduser('~/long/tedious/path/to/xyz'))
5
Then you can do:
tdi@bayes:/home/$> go tdi tdi@bayes:/home/tdi$> go tdi