Search code examples
linuxbashpowershellterminalzsh

When using PowerShell on Linux, is there a way to set the shell $PWD on exit of the PS script?


When running a PowerShell script from bash, is there a way to have PowerShell set the current directory of the calling shell up exit?

I have tried the following things (independently, not all at once)

#!/usr/bin/env pwsh 
# myscript.ps1

$desiredPath = "/the/path/I/Want"
& cd $desiredPath
& Set-Location $desiredPath
& zsh -c 'cd ${clonePath}'

Unfortunately, the end result always ends up being back at the prior $PWD.

I am sure I could return the path from the script and then pipe it to another command, but I am trying to find out if there is a way to accomplish this without having to do that, as I have the scripts folder on my path so I can simply call myscript.ps1 arg1 arg2.


Solution

  • There is no way for a subprocess to modify the environment of its parent process without cooperation from the parent; but if you can get the parent to cooperate, you can pass back an expression for it to evaluate.

    (I'm not very conversant in PowerShell so I am putting a simple Python script here instead; but you should easily see how to replace it with PowerShell.)

    cd "$(python -c 'print("/tmp/fnord")')"
    

    or more generally

    eval $(python -c 'print("cd /tmp/fnord")')
    

    but you really should avoid eval in most circumstances if at all feasible, and then make really sure you can completely trust its output if you can't avoid it.

    Needless to say, the subprocess could do something a lot more complex, as long as it prints the expression you want to pass back to the parent (and nothing else) to standard output during its execution.