Perl change working directory of caller

◇◆丶佛笑我妖孽 提交于 2019-12-04 04:41:19

问题


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?


回答1:


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.




回答2:


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. :)




回答3:


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)




回答4:


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.


来源:https://stackoverflow.com/questions/5955389/perl-change-working-directory-of-caller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!