Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the terminal working directory with cli script?

Tags:

php

I would like to change the directory in Linux terminal from cli script, not the PHP current working directory -- hopefully with shell_exec().

Ex: from user@host:~$ to user@host:/the/other/directory$

system() and exec() are not allowed.

This isn't working in my case:

$dir = '/the/other/directory';
shell_exec('cd '.$dir);

nor these

shell_exec('cd '.escapeshellarg($dir));
shell_exec(escapeshellcmd('cd '.$dir));
pclose(popen('cd '.$dir));

But shell_exec('ls '.$dir) gives me the list in that directory. Any trickery?

like image 448
kodeart Avatar asked Dec 05 '25 15:12

kodeart


1 Answers

When you're executing several commands like you are doing:

shell_exec('cd '.escapeshellarg($dir));
shell_exec(escapeshellcmd('cd '.$dir));

It won't work. The first command has nothing to do with the second one, so you can't use the results of the 1st command to execute the 2nd command.

If you want to execute a chain of commands, use the pipe symbol | like:

echo shell_exec("ls /etc/apache2 | grep fileName");
like image 151
mr_everton Avatar answered Dec 09 '25 13:12

mr_everton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!