0

I am not sure whether the title is really make sense to this problem. My problem is simple, I want to write a perl script to change my current directory and hope the result can be kept after calling the perl script. The script looks like this:

if ($#ARGV != 0) {
    print "usage: mycd <dir symbol>";
    exit -1;
}

my $dn = shift @ARGV; 

if ($dn eq "kite") {
    my $cl = `cd ./private`;
    print $cl."\n"; 
}
else {
    print "unknown directory symbol";
    exit -1; 
}

However, my current directory doesn't change after calling the script. What is the reason? How can I resolve it?

1
  • It's not possible. You'll have to write a shell script. Commented Sep 13, 2013 at 3:18

2 Answers 2

1

No, the Perl script will be run in a subprocess so it will not be able to affect the environment of the process that called it.

There are various tricks you can use such as sourcing shell scripts (in the context of the current shell rather than a sub-process), or using bash functions and aliases, but they won't work here.

Sign up to request clarification or add additional context in comments.

Comments

0

How Perl can execute a command in the same shell with it?

Unless you have a very atypical shell, shells can only receive commands via STDIN, via its command line, and possibly via a command evaluation builtin.

The first two are out unless the Perl script is the parent of the shell, but you could use the third one indirectly as in the following example.

script.pl:

#!/usr/bin/perl
print "chdir 'private'\n";

bash script:

echo "$PWD"             # /some/dir
eval "$( script.pl )"
echo "$PWD"             # /some/dir/private

Of course, if you use bash, you could hide the details in a shell function.

mycd () {
    eval "$( mycd.pl "$@" )"
}

Allowing you use to use

mycd

or even

mycd foo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.