3

I want to write a perl script that changes its working directory to somewhere else, does something, and then leaves me in that directory after I call it from the shell. chdir only does the first part. How do I change the working directory of the caller?

pythonic metaphor
  • 10,296
  • 18
  • 68
  • 110

4 Answers4

9

This is possible.

However, you would have to open of one of the /dev/mem devices in read/write mode, find the right place in memory that stores the parent process’s [dev,ino] pair for its cwd, and poke it with the new one.

And even if you managed, I doubt you’d be able to look yourself in the mirror the next morning. I sure know I never could. :) Still, the look of complete wonder on my co-workers’ faces was somehow worth it. I changed their shell’s prompts from one command to the next, using this method. It was just precious. They just couldn’t figure it out until I told them how I’d done it.

This is also not recommended. :)

tchrist
  • 78,834
  • 30
  • 123
  • 180
  • 1
    I hope you haven't published the code. For, when such scripts ever became common, it would definitely be time to switch to another OS. OTOH, fortunately, not everybody is root (you would need to be root for that, wouldn't you?) – Ingo May 10 '11 at 20:45
  • @Ingo: Yes, you need to be root to do this. – tchrist May 10 '11 at 22:52
5

What you want to do is not possible. The closest thing would be to write some bash that does what you want and then in the calling shell, source it instead of running it. Software cannot affect the shell that calls it.

Daenyth
  • 35,856
  • 13
  • 85
  • 124
  • 1
    “Not possible” is not **super-strictly** true. I’ve done this kind of naughtiness. However, anybody for whom that exemption from the normal rules and regulations did not apply certainly wouldn’t apply wouldn’t be asking about it here. It’s definitely best if they *think* it not possible: consider if they tried and missed. :) – tchrist May 10 '11 at 20:31
5

Wrap your perl script in a shell script, change directory from the bash script before executing the perl script, and source the script.

So instead of a Perl script like:

#!/usr/bin/perl
# my_program.pl ...
chdir "/my/directory";
...

Use, say, a bash script like:

#!/usr/bin/bash
cd /my/directory
perl my_program.pl "$@"

and source the script when you call it, i.e.

$ source my_bash.sh

or

$ . my_bash.sh

(Now you could use the heredoc syntax and put it all into one script:

#!/usr/bin/bash
cd /my/directory
perl <<EOF
... include your perl script here ...
EOF

But I don't think you could use @ARGV variables)

mob
  • 117,087
  • 18
  • 149
  • 283
2

You can do the followng to simulate the effect:

  1. Call your script with exec
  2. In your script, instead of exiting, exec a new shell.
Ingo
  • 36,037
  • 5
  • 53
  • 100