Reputation: 1903
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?
Upvotes: 3
Views: 2109
Reputation: 73
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");
Upvotes: 2
Reputation: 2131
If you mean you want to change the parent shell's directory by calling a php cli script, then you can't do that. What you could do is at best:
shell> eval `your/cli/script`
and in your script do something like
<?php
...
echo "cd $dir"
?>
Upvotes: 0
Reputation: 1639
Local changes made by shell_exec only apply to that php process and therefore ls would fetch from that other directory. But when you exit the php, you are back to bash who never really cares what process does.
I doubt you can change bash's current directory from outside. If you need to run bash in other directory, you could try this inside your php:
system('gnome-terminal --working-directtory=/home/doom');
this will start another terminal in new dir but script will wait till you quit this shell.
Upvotes: 0