perl_lover has asked for the wisdom of the Perl Monks concerning the following question:

can any one tell me how to change current shell's pwd ? I tried with following and ended in vein
@output = `cd /home/test/`;
system('cd /home/test');
I want current shell's pwd to be changed

Replies are listed 'Best First'.
Re: How to change Current Shell's Pwd ?
by Ytrew (Pilgrim) on Feb 07, 2005 at 07:04 UTC
    When you use backticks or the system() function, you're starting up a command shell for your operating system, changing the current directory of the command shell, then exiting the command shell and returning to perl. Perl's notion of the current directory doesn't change.

    If you want the present working directory that perl uses to change, you need to use the chdir() function.

    In your example, you'ld want something like:

    $status = chdir("/home/test"); # next, check status to see if we successfuly changed directory. die("Can't change to directory /home/test:$!") unless($status);

    You might want to double check the documentation to see what the return value of chdir() is like, but I think that's right: then again, I'm typing from memory at 2:00 am. ;-)

    Hope that helps,
    --
    Ytrew

Re: How to change Current Shell's Pwd ?
by Corion (Patriarch) on Feb 07, 2005 at 07:36 UTC

    This is a FAQ:

    perldoc -q directory

    I {changed directory, modified my environment} in a perl script. How come the change disappeared when I exited the script? How do I get my changes to be visible?

    In the strictest sense, it can't be done--the script executes as a different process from the shell it was started from. Changes to a process are not reflected in its parent--only in any children created after the change. There is shell magic that may allow you to fake it by eval()ing the script's output in your shell; check out the comp.unix.questions FAQ for details.

    In principle, changing the enclosing shell is workable, if your program outputs a new shell script, which the enclosing shell executes:

    #!/usr/bin/ksh echo "Doing what the Perl script tells me" $(perl-script.pl)
    #!/usr/bin/perl -w print 'cd ~';
Re: How to change Current Shell's Pwd ?
by Anonymous Monk on Feb 07, 2005 at 10:07 UTC
    can any one tell me how to change current shell's pwd ?
    Type:
    cd /path/to/new/directory
    at your current shell's prompt.

    Be very, very glad that processes can't change the current working directory of other processes. Or else you would need to check your working directory each and every time your program called another program. Not to mention that doing a 'chdir', or accessing a file using a non-absolute path would be wrong between doing a fork and its matching SIGCHLD, as the child process might have changed the current working directory of the parent.