1

I like to do something like this in python or bash, where the program transform the given file path and move the current shell.

ulka:~/scc/utils$ python prog.py some_path1
ulka:some_path2$

Here

some_path1 -> prog.py -> some_path2

I tried with subprocess.call or os.chdir, but it's not work, any idea will be appreciated.

2
  • 2
    you can't do that. cd is built-in. Commented Mar 21, 2017 at 20:32
  • 1
    Your python code runs in its own child process. It can't cd its parent process Commented Mar 21, 2017 at 20:32

2 Answers 2

2

Since python runs in its own process, it won't be able to change the current directory of your shell. However, you could do something like this:

change_path() {
    # prog.py figures out the real path that you want and prints
    # it to standard output
    local new_path=$(python prog.py some_path1)  # could use an argument "$1"
    cd "$new_path"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Great, I like this idea.
nice solution for a near impossible problem. @Ulka accept the answer if you think it's the best one.
1

It's possible for a shell script to change your shell's current working directory if you run it with source or .. If you run your script like this, a cd command will be all you need. If you're running a shell script without source or ., or if you're running anything that's not a shell script, then there's no nice way to do it, and you'd be forced to resort to nasty hacks like injecting into the process with a debugger (not recommended, but see How do I set the working directory of the parent process? and/or https://unix.stackexchange.com/questions/281994/changing-the-current-working-directory-of-a-certain-process if you really must do this).

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.