0

I created a script using PHP CLI that I would like to have cd me into a directory based upon my command line input.

While I can get the PHP execution commands to echo output (e.g. echo ls -al), I cannot get them to run cd.

I have searched a lot online to find the solution, but have come up empty.

All Sines
  • 3
  • 1
  • 4
  • 1
    Afaik `cd` is a builtin. You could prefix it with bash: `/bin/bash -c 'cd ; ls'`. That could work, not sure. – ZeissS Nov 25 '12 at 15:27

2 Answers2

4

You can't use cd as it would run in a subshell, and the changed working directory would be lost when you returned to PHP before issuing the next command.

Use chdir instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks for the quick reply, everyone. I'll just create a bash script instead. – All Sines Nov 25 '12 at 16:54
  • For anyone with a similar goal, my solution was to abandon PHP CLI for this. The `chdir` function changes the directory pointer within the PHP script (not my desired result here). Bash scripts using "sh" command also did not work. I had to use "source" command instead (note PHP CLI apparently does not allow execution of source command). My end result is basically `source goto-dir.sh dirname`, which executes bash code `cd /path/$1/web` (web is the docroot, $1 is the project name -- I hope to have a lot of projects, and need a quick way to get to any chosen docroot). – All Sines Nov 25 '12 at 23:08
1

You need to run chdir from php, running cd from exec, system, shell_exec etc. only change directories in subprocesses called by php, every new system call will start in php current working directory.

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85