Mark Walet
Mark Walet

Reputation: 1186

Simulate `cd` command with PHP

I am making a CLI-tool for work using the symfony/console composer package. (Much like laravel/installer)

The goal of this tool is to improve the daily workflow for my coworkers.

My [COMPANY] install command installs all active repositories in the current working directory. I save this directory in a configuration file on the home directory.

I now want to add a [COMPANY] cd command which should simulate an actual cd command by changing the current directory of my terminal to the install directory. So far, I have tried the following:

What I already tried

protected function handle(): void
{
    $config = new Config;
    $path = $config->get('directory');

    if (is_null($path)) {
        $this->error("It seems like you didn't install the [COMPANY] projects. Take a look at the `[COMPANY] install` command.");
        exit;
    }

    // These options do not work because they are executed in an isolated sub-process.
    chdir($path);
    exec("cd $path");
    shell_exec("cd $path");

    $this->info("Changed working directory to $path");
}

The chdir() method only changes the working directory of the current php script. While exec() starts a completely isolated process.

Desired behaviour

~                     cd ~/Development/Company
~/Development/Company company install
~/Development/Company cd ~
~                     company cd
~/Development/Company

My question: Is this kind of behavior even possible with PHP? And if so, how can I achieve this.

Thanks in advance.

Upvotes: 0

Views: 1053

Answers (1)

cweiske
cweiske

Reputation: 31078

No, you cannot change the working directory of a terminal by running a script in it.

cd is a command built into your shell, not an external command in e.g. /bin.

Upvotes: 2

Related Questions