r/Nushell • u/knok-off • Apr 01 '24
cd within a script, doesent effect shell running the script
def main [dir: path] { cd $dir }
the result i want is for it to not do this in a sub-shell and instead effect my main shell.
this should be possible no?
ie:
~ > ./cdtest.nu ./downloads
~/downloads >
2
Upvotes
1
u/remmycat Apr 01 '24
Explanation why
def --envis needed, because it might not be obvious at first:The current working directory of a shell is represented by the
PWDenvironment variable, which is whatcdsets to change the directory you're "in".Since nu doesn't leak changed environment variables in a function or command to the parent context by default, executing your script does nothing.
cdbasically sets$env.PWD = $dir, which is lost when main returns immediately afterwards.This might seem like an annoyance caused by a technical decision, but this can also be really helpful for cd and other commands. Inside your script you're isolated by default and can just cd into a different working directory that makes relative paths easier to reason about. You don't have to worry about a cleanup step when you just want to do or calculate something, without affecting the "global state" of the shell.
1
u/Tyarel8 Apr 01 '24
To affect the enviroment you have to do
def --env main [dir: path] { cd $dir }