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

Dear Monks, I need to write a perl-script that changes to a different directory. When this script stops, it should leave the shell in that new directory! Is this possible ? Thanks luca

Replies are listed 'Best First'.
Re: Change Directory
by Zaxo (Archbishop) on Jul 19, 2005 at 10:16 UTC

    No. A child process cannot affect the state of the parent in POSIX.

    You can source, or . (dot) a shell script to do that.

    After Compline,
    Zaxo

      In your file, no splatline needed,

      # ~/file.rc # do stuff chdir /path/to # do more stuff
      Then on the command line,
      ~>$ source file.rc /path/to>$

      After Compline,
      Zaxo

      Thanks, but I tried to do it with source via a shell script, like
      # main
      #! /bin/sh

      source "./changeDir" ;

      # file changeDir
      cd a

      But that didn't work, can you tell me why ?

      Luca
Re: Change Directory
by merlyn (Sage) on Jul 19, 2005 at 11:43 UTC
    FAQ!

    Found in /opt/perl/snap/lib/5.8.7/pods/perlfaq8.pod

    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? (Unix)
    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.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Change Directory
by Anonymous Monk on Jul 19, 2005 at 10:51 UTC
    Using a Perl script? No, that's not possible. But if you want to settle for the next best thing: having a new shell (with inherited environment variables) then it is:
    #!/usr/bin/perl chdir shift or die "Failed to chdir: $!"; exec "/usr/bin/sh" or die "Failed to exec /usr/bin/sh: $!"; __END__
    Save the above program in a file (say dir-changer), make it executable and then type, from the command line:
    exec ./dir-changer new-directory
    The result ought to be a new shell, with new-directory as its current directory.