3

我想编写一个 perl 脚本,将其工作目录更改为其他位置,执行某些操作,然后在我从 shell 调用它后将我留在那个目录中。 chdir只做第一部分。如何更改调用者的工作目录?

4

4 回答 4

9

可能的。

但是,您必须以/dev/mem读/写模式打开其中一个设备,在内存中找到存储父进程[dev,ino]对的正确位置cwd,然后用新设备戳它。

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

于 2011-05-10T20:30:08.683 回答
5

你想做的事情是不可能的。最接近的方法是编写一些 bash 来执行您想要的操作,然后在调用 shell 中获取它而不是运行它。软件不能影响调用它的 shell。

于 2011-05-10T19:30:32.150 回答
5

将您的 perl 脚本包装在 shell 脚本中,在执行 perl 脚本之前从 bash 脚本更改目录,然后获取脚本。

因此,而不是像这样的 Perl 脚本:

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

比如说,使用 bash 脚本,例如:

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

并在您调用它时获取脚本,即

$ source my_bash.sh

或者

$ . my_bash.sh

(现在您可以使用 heredoc 语法并将其全部放入一个脚本中:

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

但我不认为你可以使用@ARGV变量)

于 2011-05-10T20:14:31.897 回答
2

您可以执行以下操作来模拟效果:

  1. 用 exec 调用你的脚本
  2. 在您的脚本中,不要退出,而是执行一个新的 shell。
于 2011-05-10T19:32:29.270 回答